package com.info.zhiduoduo.core.service.common;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.FileUtils;
import com.baomidou.mybatisplus.mapper.Condition;
import com.info.zhiduoduo.common.configs.DocConfig;
import com.info.zhiduoduo.common.configs.UploadPathConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.crowdsource.CrowdsourceUserType;
import com.info.zhiduoduo.common.constants.project.CalcAmountType;
import com.info.zhiduoduo.common.constants.project.ProjectType;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.utils.*;
import com.info.zhiduoduo.common.utils.poi.DocUtils;
import com.info.zhiduoduo.common.utils.seal.SealUtil;
import com.info.zhiduoduo.core.dto.contract.CrowdSourceInfo;
import com.info.zhiduoduo.core.dto.contract.CrowdSourceInfoDto;
import com.info.zhiduoduo.repository.dto.company.CompanyDetailDto;
import com.info.zhiduoduo.repository.dto.crowdsource.CrowdsourceContractDto;
import com.info.zhiduoduo.repository.dto.crowdsource.CrowdsourceInfoDto;
import com.info.zhiduoduo.repository.dto.crowdsource.ExportProjectAcceptanceDto;
import com.info.zhiduoduo.repository.dto.crowdsource.ExportProjectAcceptanceItemDto;
import com.info.zhiduoduo.repository.dto.crowdsource.ProjectAttachmentDto;
import com.info.zhiduoduo.repository.dto.crowdsource.ProjectContractDataDto;
import com.info.zhiduoduo.repository.dto.crowdsource.ProjectContractModeDto;
import com.info.zhiduoduo.repository.dto.entrustmentproject.EntrustmentProjectItemReduceDto;
import com.info.zhiduoduo.repository.dto.entrustmentproject.ProjectEntrusteeInfoDto;
import com.info.zhiduoduo.repository.dto.maker.MakerDetailDto;
import com.info.zhiduoduo.repository.dto.taxer.TaxerInvoiceDto;
import com.info.zhiduoduo.repository.entity.company.Company;
import com.info.zhiduoduo.repository.entity.company.CompanyAccount;
import com.info.zhiduoduo.repository.entity.company.CompanyProject;
import com.info.zhiduoduo.repository.entity.crowdsource.Crowdsource;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceAccount;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceCompanyParty;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceFile;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceInvoice;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceProject;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceProjectItem;
import com.info.zhiduoduo.repository.entity.entrustmentproject.EntrustmentProject;
import com.info.zhiduoduo.repository.entity.entrustmentproject.EntrustmentProjectBlock;
import com.info.zhiduoduo.repository.entity.entrustmentproject.EntrustmentProjectItem;
import com.info.zhiduoduo.repository.entity.foreign.ForeignInvoice;
import com.info.zhiduoduo.repository.entity.maker.Maker;
import com.info.zhiduoduo.repository.entity.maker.MakerAccount;
import com.info.zhiduoduo.repository.entity.maker.MakerBankcard;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.entity.system.BusinessManager;
import com.info.zhiduoduo.repository.mapper.company.CompanyMapper;
import com.info.zhiduoduo.repository.mapper.company.CompanyProjectMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceAccountMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
import com.info.zhiduoduo.repository.mapper.entrustmentproject.EntrustmentProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.taxer.TaxerInvoiceMapper;

import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class DocService extends BaseService {

	@Autowired
	DocConfig docConfig;

	@Autowired
	ResourceLoader resourceLoader;

	@Autowired
	TaxerInvoiceMapper taxerInvoiceMapper;

	@Resource
	UploadPathConfig uploadPathConfig;

	@Resource
	CrowdsourceProjectMapper crowdsourceProjectMapper;
	@Autowired
	CrowdsourceProjectItemMapper crowdsourceProjectItemMapper;
	@Resource
	MakerMapper makerMapper;
	@Resource
	CrowdsourceAccountMapper crowdsourceAccountMapper;
	@Resource
	CompanyMapper companyMapper;
	@Resource
	CompanyProjectMapper projectMapper;
	@Resource
	EntrustmentProjectItemMapper entrustmentProjectItemMapper;

	private String generateContractNo(CompanyProject project) {
		return "ZDD" + DateUtil.formatToYYYYMMDD2(project.getCreatetime()) + project.getProjectid();
	}

	private String generateContractNo(EntrustmentProject project) {
		return "WT" + DateUtil.formatToYYYYMMDD2(project.getCreatetime()) + project.getId();
	}

	private String generateContractNo(TaxerInvoiceDto invoice) {
		return "JSX" + DateUtil.formatToYYYYMMDD2(invoice.getCreatetime()) + invoice.getInvoiceid();
	}

//	/**
//	 * 下载 项目合同
//	 *
//	 * @param response
//	 * @param projectid
//	 */
//	public void downloadContract(HttpServletResponse response, int projectid) {
//		CompanyProject project = new CompanyProject().selectById(projectid);
//		if (project == null) {
//			returnResponse(response, StatusMsg.StatusMsg_302);
//			return;
//		}
//
//		CompanyDetailDto company = companyMapper.getCompanyInfo(project.getCompid());
//		if (company == null) {
//			returnResponse(response, StatusMsg.StatusMsg_302);
//			return;
//		}
//
//		MakerStudio studio = new MakerStudio().selectById(project.getUserid());
//		if (studio == null) {
//			returnResponse(response, StatusMsg.StatusMsg_201);
//			return;
//		}
//
//		File contractDocFile = getOrCreateContractFile(project, company, studio, null);
//
//		if (contractDocFile == null) {
//			returnResponse(response, StatusMsg.StatusMsg_199);
//			return;
//		}
//
//		//contract doc exists, download
//		try {
//			downloadFile(response, contractDocFile);
//		} catch (Exception e) {
//			e.printStackTrace();
//			returnResponse(response, optFailSmartResult());
//		}
//	}

	/**
	 * 下载委托接单项目合同
	 *
	 * @param response
	 * @param projectItemid 委托接单子项目id
	 */
	public void downloadEntrustProjectContract(HttpServletResponse response, int projectItemid) {
		EntrustmentProjectItem projectItem = new EntrustmentProjectItem().selectById(projectItemid);
		if (projectItem == null) {
			returnResponse(response, StatusMsg.StatusMSG_1101);
			return;
		}

		CrowdsourceInfoDto crowdsourceAccount = crowdsourceAccountMapper.getInfo(projectItem.getCrowdsourceid());
		if (crowdsourceAccount == null) {
			returnResponse(response, StatusMsg.StatusMsg_601);
			return;
		}

		MakerDetailDto maker = makerMapper.getUserDetail(projectItem.getEntrusteeId());
		if (maker == null) {
			returnResponse(response, StatusMsg.StatusMsg_201);
			return;
		}

		File contractDocFile = getOrCreateEntrustContractFile(projectItem, crowdsourceAccount, maker, response);

		if (contractDocFile == null) {
			returnResponse(response, StatusMsg.StatusMsg_199);
			return;
		}

		//contract doc exists, download
		try {
			downloadFile(response, contractDocFile);
		} catch (Exception e) {
			e.printStackTrace();
			returnResponse(response, optFailSmartResult());
		}
	}

	public File getOrCreateEntrustContractFile(EntrustmentProjectItem projectItem, CrowdsourceInfoDto crowdsource, MakerDetailDto maker,
											   HttpServletResponse response) {

		String contractDocName = "委托协议" + "_" + projectItem.getId() + "_" + projectItem.getCreatetime().getTime() + ".doc";

		//generate data map
		Date contractDate = projectItem.getDispatchTime();
		if (contractDate == null) contractDate = projectItem.getCreatetime();
		BigDecimal serviceCharge = projectItem.getTaxInclusiveAmount().setScale(2, BigDecimal.ROUND_HALF_UP);

		return generateEntrustDocFileInternal(response, contractDocName, projectItem.getCrowdsourceName(), crowdsource.getIdno(),
				crowdsource.getPhone(), crowdsource.getAcctno(), projectItem.getEntrusteeName(), projectItem.getEntrusteeStudio(),
				maker.getIdno(), maker.getPhone(), contractDate, projectItem.getName(), projectItem.getContent(), serviceCharge);

	}

//	public File getOrCreateContractFile(CompanyProject project, CompanyDetailDto company, MakerStudio studio, HttpServletResponse response) {
//
//		String contractDocName = project.getProjectname() + "_" + project.getProjectid() + "_" + project.getCreatetime().getTime() +
//				".doc";
//		String contractNo = generateContractNo(project);
//
//		//generate data map
//		Date contractDate = project.getProjectstart();
//		if (contractDate == null) contractDate = project.getCreatetime();
//		BigDecimal serviceCharge = project.getProjectamount().setScale(2, BigDecimal.ROUND_HALF_UP);
//
//		if (project.getCategoryid() == 34) {
//			// 商品交易，使用商品交易合同
//			return generateCommodityContractDocFileInternal(response, contractDocName, contractNo, company.getCompname(),
//					studio.getUsername(), contractDate, project.getProjectname(), project.getProjectintro(), serviceCharge,
//					studio.getUserid(), project.getCommodityDetailFilePath());
//		} else {
//			return generateDocFileInternal(response, contractDocName, contractNo, company.getCompname(), company.getPartyName(),
//					studio.getUsername(), contractDate, project.getProjectname(), project.getProjectintro(), serviceCharge,
//					studio.getUserid());
//		}
//
//	}

	/**
	 * 共青城推送项目时生成合同
	 *
	 * @param crowdsourceProject
	 * @param response
	 * @return
	 */
	public File getGongQingContractFile(List<CrowdsourceAccount> crowdsourceAccountList, List<MakerStudio> makerStudioList,
										CrowdsourceProject crowdsourceProject, HttpServletResponse response,
										String gongQingInvoiceContent) {

		String contractDocName =
				crowdsourceProject.getProjectName() + "-" + crowdsourceProject.getProjectid() + "-" + System.currentTimeMillis() + ".doc";

		System.out.println("填写的共青城开票内容为:" + gongQingInvoiceContent);
		System.out.println("即将生成合同:" + contractDocName);
		Date contractDate = crowdsourceProject.getCreatetime();
		BigDecimal serviceCharge = crowdsourceProject.getProjectTotalAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
		return generateGongQingDocFile(response, contractDocName, "江西武圣信息科技有限公司", crowdsourceAccountList, makerStudioList, contractDate,
				crowdsourceProject, serviceCharge, gongQingInvoiceContent);
	}

	/**
	 * 共青城推送项目时生成自然人的合同
	 *
	 * @param crowdsourceAccount
	 * @param crowdsourceProject
	 * @param response
	 * @param gongQingInvoiceContent
	 * @return
	 */
	public File getGongQingContractCrowdSourceAccountFile(CrowdsourceAccount crowdsourceAccount, CrowdsourceProject crowdsourceProject,
														  HttpServletResponse response, String gongQingInvoiceContent) {

		String contractDocName = crowdsourceProject.getProjectName() + "-" + crowdsourceProject.getProjectid() + "-" +
				crowdsourceAccount.getCrowdsourceid() + "-" + System.currentTimeMillis() + ".doc";

		System.out.println("填写的共青城开票内容为:" + gongQingInvoiceContent);
		System.out.println("即将生成合同:" + contractDocName);
		Date contractDate = crowdsourceProject.getCreatetime();
		float serviceCharge = crowdsourceProject.getProjectTotalAmount().setScale(2, RoundingMode.DOWN).floatValue();
		return getGongQingContractCrowdSourceAccountFile(response, contractDocName, "江西武圣信息科技有限公司", crowdsourceAccount, contractDate,
				crowdsourceProject, serviceCharge, gongQingInvoiceContent);
	}

	/**
	 * 共青城推送项目时生成创客合同
	 *
	 * @param crowdsourceProject
	 * @param response
	 * @return
	 */
	public File getGongQingContracMakerFile(MakerStudio makerStudio, CrowdsourceProject crowdsourceProject, HttpServletResponse response,
											String gongQingInvoiceContent) {

		String contractDocName =
				crowdsourceProject.getProjectName() + "-" + crowdsourceProject.getProjectid() + "-" + makerStudio.getUserid() + "-" +
						System.currentTimeMillis() + ".doc";

		System.out.println("填写的共青城开票内容为:" + gongQingInvoiceContent);
		System.out.println("即将生成合同:" + contractDocName);
		Date contractDate = crowdsourceProject.getCreatetime();
		//获取该条项目中该个体户的对应信息
		CrowdsourceProjectItem crowdsourceProjectItem = new CrowdsourceProjectItem().selectOne(Condition.create()
																										.eq("projectid", crowdsourceProject.getProjectid())
																										.eq("userid", makerStudio.getUserid())
																										.eq("deleted", 0));
		float serviceCharge = crowdsourceProjectItem.getProjectAmount().setScale(2, RoundingMode.DOWN).floatValue();
		return getGongQingContracMakerFile(response, contractDocName, "江西武圣信息科技有限公司", makerStudio, contractDate, crowdsourceProject,
				serviceCharge, gongQingInvoiceContent);
	}

	/**
	 * 下载 项目合同, 如果没有,则立即生成一份合同
	 *
	 * @param request
	 * @param response
	 * @param invoiceid
	 */
	public void downloadTaxerInvoiceContract(HttpServletRequest request, HttpServletResponse response, int invoiceid) {

		TaxerInvoiceDto invoice = taxerInvoiceMapper.getInvoice(invoiceid);
		if (invoice == null) {
			returnResponse(response, StatusMsg.StatusMsg_714);
			return;
		}

		File contractDocFile = getOrCreateContractFile(invoice, response);
		if (contractDocFile == null) {
			returnResponse(response, StatusMsg.StatusMsg_199);
			return;
		}

		//contract doc exists, download
		try {
			downloadFile(response, contractDocFile);
		} catch (Exception e) {
			e.printStackTrace();
			returnResponse(response, optFailSmartResult());
		}
	}

	/**
	 * 生成 发票项目合同
	 *
	 * @param invoice
	 * @param response
	 * @return
	 */
	public File getOrCreateContractFile(TaxerInvoiceDto invoice, HttpServletResponse response) {
		Date contractDate = invoice.getCreatetime();
		BigDecimal serviceCharge = invoice.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
		String contractDocName = invoice.getProjectname() + "_INVOICE_" + invoice.getInvoiceid() + ".doc";
		String contractNo = generateContractNo(invoice);

		return generateDocFileInternal(response, contractDocName, contractNo, invoice.getCompanyName(), "智圣（天津）网络科技有限公司", invoice.getUsername(),
				contractDate,
				invoice.getProjectname(), invoice.getProjectintro(), serviceCharge, invoice.getUserid());
	}

	private File generateDocFileInternal(HttpServletResponse response, String contractDocName, String contractNo, String compname,
	                                     String partyName,
										 String username, Date contractDate, String projectname, String projectContent,
										 BigDecimal serviceCharge,int userId) {

		File filePath = new File(docConfig.getDocFilePath(), DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_5));
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		contractDocName = username + "_" + contractDocName;
		File contractDocFile = new File(filePath, contractDocName);
		// File contractPdfFile = new File(filePath, contractPdfName);

		if (!contractDocFile.exists()) {
			FileUtils.delete(contractDocFile);
			// FileUtil.deleteFile(contractPdfFile);

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			if (!sealPath.exists()) {
				sealPath.mkdirs();
			}
			String compseal = compname + "_seal.png";
			String userseal = username + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			File usersealFile = new File(sealPath, userseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(compname, compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			if (!usersealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(username, usersealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			String temporaryLogin = isTemporaryLogin(userId);
			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
			Date endDate = DateUtil.localDate2Date(localDate);
			Map<String, Object> data = new HashMap<>();
			data.put("contractNo", contractNo);
			data.put("compname", compname);
			data.put("partyName", partyName);
			data.put("username", username);
			data.put("usernameAutograph", temporaryLogin.equals("") ? "" : ImgBase64Util.ImgToBase64(temporaryLogin));
			data.put("serviceCharge", serviceCharge);
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("validity", 1);
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("projectname", projectname);
			data.put("content", projectContent);
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			data.put("userseal", ImgBase64Util.ImgToBase64(usersealFile.getAbsolutePath()));

			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getTemplateName(), filePath.getAbsolutePath(), contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
			//转换成pdf
			/*try {
				DocUtils.convertDocxToPDF(contractDocFile, contractPdfFile.getPath());
			} catch (Exception e) {
				e.printStackTrace();
			}*/
		}
		return contractDocFile;
	}

	private File generateEntrustDocFileInternal(HttpServletResponse response, String contractDocName, String crowdName, String crowdIdno,
												String crowdPhone, String crowdAcctno, String makerName, String studioName,
												String makerIdno, String makerPhone, Date contractDate, String projectname,
												String projectContent, BigDecimal serviceCharge) {

		File filePath = new File(docConfig.getEntrusteeDocFilePath(), DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_5));
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		File contractDocFile = new File(filePath, contractDocName);
		// File contractPdfFile = new File(filePath, contractPdfName);

		if (!contractDocFile.exists()) {
			FileUtils.delete(contractDocFile);
			// FileUtil.deleteFile(contractPdfFile);

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			if (!sealPath.exists()) {
				sealPath.mkdirs();
			}
			String userseal = studioName + "_seal.png";
			File usersealFile = new File(sealPath, userseal);

			if (!usersealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(studioName, usersealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
			Date endDate = DateUtil.localDate2Date(localDate);
			Map<String, Object> data = new HashMap<>();
			data.put("crowdName", crowdName);
			data.put("crowdIdno", crowdIdno);
			data.put("crowdPhone", crowdPhone);
			data.put("crowdAcctno", crowdAcctno);
			data.put("makerName", makerName);
			data.put("studioName", studioName);
			data.put("makerIdno", makerIdno);
			data.put("makerPhone", makerPhone);
			data.put("serviceCharge", serviceCharge);
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("validity", 1);
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("projectname", projectname);
			data.put("content", projectContent);
			data.put("crowdseal", "");
			data.put("userseal", ImgBase64Util.ImgToBase64(usersealFile.getAbsolutePath()));

			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getEntrustContractTemplate(), filePath.getAbsolutePath(), contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
			//转换成pdf
			/*try {
				DocUtils.convertDocxToPDF(contractDocFile, contractPdfFile.getPath());
			} catch (Exception e) {
				e.printStackTrace();
			}*/
		}
		return contractDocFile;
	}

	public String isTemporaryLogin(Integer userId) {
		String electronicSignature = "";
		List<MakerAccount> userid = new MakerAccount().selectList(Condition.create().eq("userid", userId));
		if (userid != null && userid.size() > 0) {
			Integer temporaryLogin = userid.get(0).getTemporaryLogin();
			if (temporaryLogin == 1) {
				electronicSignature = uploadPathConfig.getUploadpath() + userid.get(0).getElectronicSignature();
				log.error(electronicSignature + "+=========================================");
			}
		}
		return electronicSignature;
	}

	/**
	 * 众智包  自然人开票时自动生成合同向共青城推送
	 *
	 * @param response
	 * @param contractDocName
	 * @param compname
	 * @param crowdsourceAccountList
	 * @param contractDate
	 * @param crowdsourceProject
	 * @param serviceCharge
	 * @param gongQingInvoiceContent
	 * @return
	 */
	private File generateGongQingDocFile(HttpServletResponse response, String contractDocName, String compname,
										 List<CrowdsourceAccount> crowdsourceAccountList, List<MakerStudio> makerStudioList,
										 Date contractDate, CrowdsourceProject crowdsourceProject, BigDecimal serviceCharge,
										 String gongQingInvoiceContent) {

		String format = "yyyyMMdd";
		//文件夹名称
		String folderName = "/" + DateUtil.DateToStr(format, new Date());
		//创建文件夹
		File filePath = new File(docConfig.getGongqingcheng() + folderName);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		List<CrowdSourceInfo> crowdSourceInfoList = new ArrayList<>();
		List<CrowdSourceInfoDto> crowdSourceInfoDtoList = new ArrayList<>();
		//乙方
		String userinfo = "";

		if (null != crowdsourceAccountList && !crowdsourceAccountList.isEmpty()) {
			//自然人信息
			for (CrowdsourceAccount crowdsourceAccount : crowdsourceAccountList) {
				CrowdSourceInfo crowdSourceInfo = new CrowdSourceInfo();
				crowdSourceInfo.setCrowdsourceid(crowdsourceAccount.getCrowdsourceid());
				//乙方
				if (StringUtil.isEmpty(userinfo)) {
					userinfo = crowdsourceAccount.getRealname() + crowdsourceAccount.getIdno();
				} else {
					userinfo += "，" + crowdsourceAccount.getRealname() + crowdsourceAccount.getIdno();
				}
				CrowdsourceFile positive = new CrowdsourceFile().selectOne(
						Condition.create().eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()).eq("file_type", 1));
				CrowdsourceFile otherSide = new CrowdsourceFile().selectOne(
						Condition.create().eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()).eq("file_type", 2));

				File filePositive = new File(uploadPathConfig.getUploadpath() + positive.getFilePath());
				File fileOtherSide = new File(uploadPathConfig.getUploadpath() + otherSide.getFilePath());
				crowdSourceInfo.setPositive(ImgBase64Util.ImgToBase64(filePositive.getAbsolutePath()));
				crowdSourceInfo.setOtherSide(ImgBase64Util.ImgToBase64(fileOtherSide.getAbsolutePath()));

				crowdSourceInfoList.add(crowdSourceInfo);
			}
		}

		//处理图片
		String beforePicStart = "<pkg:part pkg:name=\"/word/media/image";
		String positivePicBeforeString = "";
		String otherSidePicBeforeString = "";

		String picStrEnd = ".jpeg\" pkg:contentType=\"image/jpeg\" pkg:compression=\"store\"><pkg:binaryData>";
		String picStrEnd2 = "</pkg:binaryData></pkg:part>";
		StringBuffer positivePicBufferBefore = new StringBuffer();
		StringBuffer otherSidePicBufferBefore = new StringBuffer();

		//处理Relation
		String beforeRelationStart = "<Relationship Id=\"rId";
		String afterRelationEnd =
				"\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\" " + "Target=\"media/image";
		String afterRelationEnd2 = ".jpeg\"/>";
		String positiveRelationStringBefore = "";
		String overSideRelationStringBefore = "";
		StringBuffer positiveRelationshipBufferBefore = new StringBuffer();
		StringBuffer otherSideRelationshipBufferBefore = new StringBuffer();

		String rsidStart =
				"<w:r><w:rPr><w:rFonts w:hint=\"eastAsia\"/><w:noProof/></w:rPr><w:drawing><wp:inline distT=\"0\" distB=\"0\"" + " " +
						"distL=\"114300\" distR=\"114300\"><wp:extent cx=\"5273040\" cy=\"3419475\"/><wp:effectExtent l=\"0\" t=\"0\" " +
						"r=\"3810\"" + " " +
						"b=\"9525\"/><wp:docPr id=\"1\" name=\"图片 1\" descr=\"weixinceshi\"/><wp:cNvGraphicFramePr><a:graphicFrameLocks " +
						"noChangeAspect=\"1\" xmlns:a=\"http://schemas.openxmlformats" +
						".org/drawingml/2006/main\"/></wp:cNvGraphicFramePr><a:graphic" +
						" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"><a:graphicData uri=\"http://schemas" +
						".openxmlformats" + ".org/drawingml/2006/picture\"><pic:pic xmlns:pic=\"http://schemas.openxmlformats" +
						".org/drawingml/2006/picture\"><pic:nvPicPr><pic:cNvPr id=\"1\" name=\"图片 1\" " +
						"descr=\"weixinceshi\"/><pic:cNvPicPr><a:picLocks " +
						"noChangeAspect=\"1\"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip" + " r:embed=\"rId";
		String rsidEnd = "\"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext " +
				"cx=\"5273040\" cy=\"3419475\"/></a:xfrm><a:prstGeom " +
				"prst=\"rect\"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>";

		if (!crowdSourceInfoList.isEmpty()) {
			for (int i = 0; i < crowdSourceInfoList.size(); i++) {
				CrowdSourceInfoDto crowdSourceInfoDto = new CrowdSourceInfoDto();
				String positiveRsidBeforeString = "";
				String otherSideRsidBeforeString = "";

				positiveRsidBeforeString = rsidStart + (i + 40) + i + rsidEnd;
				crowdSourceInfoDto.setPositive(positiveRsidBeforeString);
				otherSideRsidBeforeString = rsidStart + (i + 70) + i + rsidEnd;
				crowdSourceInfoDto.setOtherSide(otherSideRsidBeforeString);

				String positivePic = crowdSourceInfoList.get(i).getPositive();
				String otherSidePic = crowdSourceInfoList.get(i).getOtherSide();

				positivePicBeforeString = beforePicStart + (i + 40) + picStrEnd + positivePic + picStrEnd2;
				otherSidePicBeforeString = beforePicStart + (i + 70) + picStrEnd + otherSidePic + picStrEnd2;

				positiveRelationStringBefore = beforeRelationStart + (i + 40) + i + afterRelationEnd + (i + 40) + afterRelationEnd2;
				overSideRelationStringBefore = beforeRelationStart + (i + 70) + i + afterRelationEnd + (i + 70) + afterRelationEnd2;

				positivePicBufferBefore.append(positivePicBeforeString);
				otherSidePicBufferBefore.append(otherSidePicBeforeString);

				positiveRelationshipBufferBefore.append(positiveRelationStringBefore);
				otherSideRelationshipBufferBefore.append(overSideRelationStringBefore);

				int crowdSourceId = crowdSourceInfoList.get(i).getCrowdsourceid();
				Crowdsource crowdsource = new Crowdsource().selectById(crowdSourceId);
				CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(
						Condition.create().eq("crowdsourceid", crowdSourceId));
				CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(Condition.create()
																									.eq("projectid", crowdsourceProject.getProjectid())
																									.eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()));

				crowdSourceInfoDto.setRealname(crowdsourceAccount.getRealname());
				crowdSourceInfoDto.setIdno(crowdsourceAccount.getIdno());
				crowdSourceInfoDto.setAcctphone(crowdsource.getPhone());
				crowdSourceInfoDto.setAmount(crowdsourceInvoice.getProjectAmount().setScale(2, RoundingMode.DOWN).floatValue());
				crowdSourceInfoDto.setInvoiceContent(gongQingInvoiceContent);
				crowdSourceInfoDto.setFlag(1);
				crowdSourceInfoDtoList.add(crowdSourceInfoDto);
			}
		}

		if (null != makerStudioList && !makerStudioList.isEmpty()) {
			//个体户(创客)信息
			for (MakerStudio makerStudio : makerStudioList) {
				CrowdSourceInfoDto crowdSourceInfoDto = new CrowdSourceInfoDto();
				//乙方
				if (StringUtil.isEmpty(userinfo)) {
					userinfo = makerStudio.getUsername();
				} else {
					userinfo += "，" + makerStudio.getUsername();
				}

				CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(
						Condition.create().eq("projectid", crowdsourceProject.getProjectid()).eq("crowdsourceid",
								makerStudio.getUserid()));
				Maker maker = new Maker().selectById(makerStudio.getUserid());
				crowdSourceInfoDto.setAmount(crowdsourceInvoice.getProjectAmount().setScale(2, RoundingMode.DOWN).floatValue());
				crowdSourceInfoDto.setInvoiceContent(gongQingInvoiceContent);
				crowdSourceInfoDto.setRealname(makerStudio.getUsername());
				crowdSourceInfoDto.setAcctphone(maker.getPhone());
				crowdSourceInfoDto.setCreditcode(makerStudio.getCreditcode());
				crowdSourceInfoDto.setFlag(2);
				crowdSourceInfoDtoList.add(crowdSourceInfoDto);
			}
		}

		File contractDocFile = new File(filePath, contractDocName);

		if (!contractDocFile.exists()) {

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			String compseal = compname + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(compname, compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}

			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
			Date endDate = DateUtil.localDate2Date(localDate);

			Map<String, Object> data = new HashMap<>();
			data.put("positivePicDataBefore", positivePicBufferBefore.toString());
			data.put("otherSidePicDataBefore", otherSidePicBufferBefore.toString());
			data.put("positiveRelationship", positiveRelationshipBufferBefore.toString());
			data.put("otherSideRelationship", otherSideRelationshipBufferBefore.toString());

			data.put("invoiceContent", gongQingInvoiceContent);
			data.put("compname", compname);
			data.put("content", crowdsourceProject.getProjectDesc());
			data.put("username", userinfo);
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("validity", 1);
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("projectname", crowdsourceProject.getProjectName());
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			data.put("serviceCharge", serviceCharge);
			data.put("userList", crowdSourceInfoDtoList);
			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getGongQingtemplateName(), docConfig.getGongqingcheng() + folderName, contractDocName);
				System.out.println("生成的合同路径为：" + docConfig.getGongqingcheng() + folderName + File.separator + contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return contractDocFile;
	}

	private void returnResponse(HttpServletResponse response, StatusMsg statusMsg) {
		if (response != null) {
			returnResponse(response, smartResult(statusMsg));
		}
	}

	/**
	 * 共青城推送项目时生成自然人的合同
	 *
	 * @param response
	 * @param contractDocName
	 * @param compname
	 * @param crowdsourceAccount
	 * @param contractDate
	 * @param crowdsourceProject
	 * @param serviceCharge
	 * @param gongQingInvoiceContent
	 * @return
	 */
	private File getGongQingContractCrowdSourceAccountFile(HttpServletResponse response, String contractDocName, String compname,
														   CrowdsourceAccount crowdsourceAccount, Date contractDate,
														   CrowdsourceProject crowdsourceProject, float serviceCharge,
														   String gongQingInvoiceContent) {

		String format = "yyyyMMdd";
		//文件夹名称
		String folderName = "/" + DateUtil.DateToStr(format, new Date());
		//创建文件夹
		File filePath = new File(docConfig.getGongqingcheng() + folderName);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		Crowdsource crowdsource = new Crowdsource().selectById(crowdsourceAccount.getCrowdsourceid());
		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(Condition.create()
																							.eq("projectid", crowdsourceProject.getProjectid())
																							.eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()));
		//乙方名字
		String userinfo = crowdsourceAccount.getRealname() + crowdsourceAccount.getIdno();

		//乙方身份证图片
		CrowdsourceFile positive = new CrowdsourceFile().selectOne(
				Condition.create().eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()).eq("file_type", 1));
		CrowdsourceFile otherSide = new CrowdsourceFile().selectOne(
				Condition.create().eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()).eq("file_type", 2));
		File filePositive = new File(uploadPathConfig.getUploadpath() + positive.getFilePath());
		File fileOtherSide = new File(uploadPathConfig.getUploadpath() + otherSide.getFilePath());

		CrowdSourceInfoDto crowdSourceInfoDto = new CrowdSourceInfoDto();
		crowdSourceInfoDto.setPositive(ImgBase64Util.ImgToBase64(filePositive.getAbsolutePath()));
		crowdSourceInfoDto.setOtherSide(ImgBase64Util.ImgToBase64(fileOtherSide.getAbsolutePath()));
		crowdSourceInfoDto.setRealname(crowdsourceAccount.getRealname());
		crowdSourceInfoDto.setIdno(crowdsourceAccount.getIdno());
		crowdSourceInfoDto.setAcctphone(crowdsource.getPhone());
		crowdSourceInfoDto.setAmount(crowdsourceInvoice.getProjectAmount().setScale(2, RoundingMode.DOWN).floatValue());
		crowdSourceInfoDto.setInvoiceContent(gongQingInvoiceContent);

		File contractDocFile = new File(filePath, contractDocName);

		if (!contractDocFile.exists()) {
			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			String compseal = compname + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(compname, compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
			Date endDate = DateUtil.localDate2Date(localDate);

			Map<String, Object> data = new HashMap<>();
			data.put("invoiceContent", gongQingInvoiceContent);
			data.put("compname", compname);
			data.put("content", crowdsourceProject.getProjectDesc());
			data.put("username", userinfo);
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("validity", 1);
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("projectname", crowdsourceProject.getProjectName());
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			data.put("serviceCharge", serviceCharge);
			data.put("user", crowdSourceInfoDto);
			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getGongQingCrowdSourceContractTemplateName(),
						docConfig.getGongqingcheng() + folderName,
						contractDocName);
				System.out.println("生成的合同路径为：" + docConfig.getGongqingcheng() + folderName + File.separator + contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return contractDocFile;
	}

	/**
	 * 共青城推送项目时生成创客合同
	 *
	 * @param response
	 * @param contractDocName
	 * @param compname
	 * @param makerStudio
	 * @param contractDate
	 * @param crowdsourceProject
	 * @param serviceCharge
	 * @param gongQingInvoiceContent
	 * @return
	 */
	private File getGongQingContracMakerFile(HttpServletResponse response, String contractDocName, String compname,
											 MakerStudio makerStudio,
											 Date contractDate, CrowdsourceProject crowdsourceProject, float serviceCharge,
											 String gongQingInvoiceContent) {

		String format = "yyyyMMdd";
		//文件夹名称
		String folderName = "/" + DateUtil.DateToStr(format, new Date());
		//创建文件夹
		File filePath = new File(docConfig.getGongqingcheng() + folderName);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(
				Condition.create().eq("projectid", crowdsourceProject.getProjectid()).eq("crowdsourceid", makerStudio.getUserid()));
		Maker maker = new Maker().selectById(makerStudio.getUserid());
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", makerStudio.getUserid()));
		MakerBankcard makerBankcard = new MakerBankcard().selectOne(Condition.create().eq("userid", makerStudio.getUserid()));

		//创客电子签名
		File electronicSignature = new File(uploadPathConfig.getUploadpath() + makerAccount.getElectronicSignature());
		//乙方工作室名称
		String userinfo = makerStudio.getUsername();
		CrowdSourceInfoDto crowdSourceInfoDto = new CrowdSourceInfoDto();
		crowdSourceInfoDto.setAmount(crowdsourceInvoice.getProjectAmount().setScale(2, RoundingMode.DOWN).floatValue());
		crowdSourceInfoDto.setInvoiceContent(gongQingInvoiceContent);
		crowdSourceInfoDto.setRealname(makerStudio.getUsername());
		crowdSourceInfoDto.setAcctphone(maker.getPhone());
		crowdSourceInfoDto.setCreditcode(makerStudio.getCreditcode());
		crowdSourceInfoDto.setIndividualAccountNumber(makerAccount.getIndividualAccountNumber());
		crowdSourceInfoDto.setElectronicSignature(ImgBase64Util.ImgToBase64(electronicSignature.getAbsolutePath()));
		crowdSourceInfoDto.setBankInfo(makerBankcard.getBankname() + " " + makerBankcard.getAcctno());

		File contractDocFile = new File(filePath, contractDocName);
		if (!contractDocFile.exists()) {

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			String compseal = compname + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(compname, compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}

			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
			Date endDate = DateUtil.localDate2Date(localDate);

			Map<String, Object> data = new HashMap<>();

			data.put("invoiceContent", gongQingInvoiceContent);
			data.put("compname", compname);
			data.put("content", crowdsourceProject.getProjectDesc());
			data.put("username", userinfo);
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("validity", 1);
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("projectname", crowdsourceProject.getProjectName());
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			data.put("serviceCharge", serviceCharge);
			data.put("user", crowdSourceInfoDto);
			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getGongQingMakerContractTemplateName(), docConfig.getGongqingcheng() + folderName,
						contractDocName);
				System.out.println("生成的合同路径为：" + docConfig.getGongqingcheng() + folderName + File.separator + contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return contractDocFile;
	}

	/**
	 * 生成 发包方与商户 之间的合同
	 *
	 * @param projectId
	 * @param response
	 */
	public void getCompanyAndWuShengContract(int projectId, HttpServletResponse response) {
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectId);
		//获取公司信息
		Company company = new Company().selectById(crowdsourceProject.getCompid());
		//获取企业详细信息
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", crowdsourceProject.getCompid()));

		File contractDocFile = getBusinessContractFile(response, company, companyAccount, crowdsourceProject);
		if (contractDocFile == null) {
			returnResponse(response, StatusMsg.StatusMsg_199);
			return;
		}

		try {
			downloadFile(response, contractDocFile);
		} catch (Exception e) {
			e.printStackTrace();
			returnResponse(response, optFailSmartResult());
		}
	}

	/**
	 * 生成 发包方与商户 之间的合同
	 *
	 * @param response
	 * @param company
	 * @param companyAccount
	 * @param crowdsourceProject
	 * @return
	 */
	public File getBusinessContractFile(HttpServletResponse response, Company company, CompanyAccount companyAccount,
										CrowdsourceProject crowdsourceProject) {
		String contractDocName =
				crowdsourceProject.getProjectName() + "-" + crowdsourceProject.getProjectid() + "-(发包方与商户)-" + System.currentTimeMillis() +
						".doc";
		System.out.println("即将生成合同:" + contractDocName);
		//		Date contractDate = crowdsourceProject.getCreatetime();
		Date contractDate = companyAccount.getContractStartDate();
		float serviceCharge = crowdsourceProject.getProjectTotalAmount().setScale(2, RoundingMode.DOWN).floatValue();

		String format = "yyyyMMdd";
		//文件夹名称
		String folderName = "/" + DateUtil.DateToStr(format, new Date());
		//创建文件夹
		File filePath = new File(docConfig.getGongqingcheng() + folderName);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		File contractDocFile = new File(filePath, contractDocName);
		if (!contractDocFile.exists()) {
			//检查甲方公章是否生成
			File sealPath = new File(docConfig.getSealPath());
			String partyASeal = company.getCompname() + "_seal.png";
			File compsealFile = new File(sealPath, partyASeal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(company.getCompname(), compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			//			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
			//			Date endDate = DateUtil.localDate2Date(localDate);
			Date endDate = companyAccount.getContractEndDate();

			Map<String, Object> data = new HashMap<>();
			data.put("partyAName", company.getCompname());
			data.put("partyAAdress", company.getCompaddress());
			data.put("legalName", companyAccount.getRealname());
			data.put("contactNumber", company.getContactphone());
			data.put("partyASeal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			data.put("serviceRate", Integer.parseInt(new DecimalFormat("0").format(company.getBaseTaxRate() * 100)));
			data.put("projectAmount", serviceCharge);
			data.put("partyAEmail", company.getCompemail());
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getBusinessContractTemplateName(), docConfig.getGongqingcheng() + folderName,
						contractDocName);
				System.out.println("生成的合同路径为：" + docConfig.getGongqingcheng() + folderName + File.separator + contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return contractDocFile;
	}

	/**
	 * 生成合同文件,然后下载
	 *
	 * @param contractFile
	 * @param data
	 */
	public void generateContract(File contractFile, Map<String, Object> data) throws Exception {

		// String templatePath = orderConfig.getTemplateName();
		String templatePath = "/Users/neyxixi/Downloads/Bob/项目文档/ /contractdoc/contract_template.docx";
		XWPFDocument template = DocUtils.open(templatePath);
		//模板先转成输出流再输入, 防止直接在模板上修改数据.
		XWPFDocument xdoc = DocUtils.open(DocUtils.exportToIs(template));
		if (xdoc == null) {
			LogUtil.info("加载模板文件失败");
			return;
		}
		List<IBodyElement> bodyElements = xdoc.getBodyElements();
		if (bodyElements == null || bodyElements.isEmpty()) {
			LogUtil.info("xdoc没有内容");
		}

		DocUtils.replaceInPara(xdoc, data);
		XWPFParagraph paragraph = xdoc.createParagraph();
		XWPFRun run = paragraph.createRun();
		run.addBreak();
		String picFile = (String) data.get("compseal");
		run.addPicture(new FileInputStream(picFile), DocUtils.getPictureType(picFile), picFile, 300, 300);
		DocUtils.write(xdoc, contractFile);

	}

	/**
	 * 下载doc文件
	 *
	 * @param response
	 * @param file
	 * @throws Exception
	 */
	public void downloadFile(HttpServletResponse response, File file) throws Exception {
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "utf-8"));
		// response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
		ServletOutputStream os = response.getOutputStream();
		FileInputStream fis = new FileInputStream(file);
		copyStream(fis, os, false);
		fis.close();
	}

	/**
	 * 下载第三方项目嘉银合同
	 *
	 * @param response
	 * @param invoiceId
	 */
	public void downloadForeignContract(HttpServletResponse response, int invoiceId) {

		ForeignInvoice invoice = new ForeignInvoice().selectById(invoiceId);
		if (null == invoice) {
			returnResponse(response, StatusMsg.StatusMsg_930);
		}
		File contractDocFile = getForeignContractFile(invoice, response);
		if (contractDocFile == null) {
			returnResponse(response, StatusMsg.StatusMsg_199);
			return;
		}
		try {
			downloadFile(response, contractDocFile);
		} catch (Exception e) {
			e.printStackTrace();
			returnResponse(response, optFailSmartResult());
		}

	}

	/**
	 * 生成第三方项目嘉银合同
	 *
	 * @param invoice
	 * @param response
	 * @return
	 */
	private File getForeignContractFile(ForeignInvoice invoice, HttpServletResponse response) {

		Date contractDate = invoice.getCreatetime();
		float serviceCharge = invoice.getAmount().setScale(2, RoundingMode.DOWN).floatValue();
		String contractDocName;
		//		if (1 == invoice.getWhetherMerge()) {
		//			contractDocName = invoice.getNameOfPartyB() + "-" + invoice.getAmount() + ".doc";
		//		} else {
		CrowdsourceAccount account = new CrowdsourceAccount().selectOne(Condition.create().eq("crowdsourceid",
				invoice.getCrowdsourceid()));
		contractDocName = account.getRealname() + "-" + invoice.getAmount() + ".doc";
		//		}
		LogUtil.info("即将生成合同:" + contractDocName);
		return gettForeignContractFile(response, invoice, contractDocName, contractDate, serviceCharge);
	}

	/**
	 * 生成第三方项目嘉银合同
	 *
	 * @param response
	 * @param invoice
	 * @param contractDocName
	 * @param contractDate
	 * @param serviceCharge
	 * @return
	 */
	private File gettForeignContractFile(HttpServletResponse response, ForeignInvoice invoice, String contractDocName, Date contractDate,
										 float serviceCharge) {

		String compname = "上海嘉捷互联网金融信息服务有限公司";
		String format = "yyyyMMdd";
		//文件夹名称
		String folderName = "/" + DateUtil.DateToStr(format, new Date());
		//创建文件夹
		File filePath = new File(docConfig.getForeignContract() + folderName);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		File contractDocFile = new File(filePath, contractDocName);

		if (!contractDocFile.exists()) {
			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			String compseal = compname + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(compname, compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(0).minusDays(-30);
			Date endDate = DateUtil.localDate2Date(localDate);

			Map<String, Object> data = new HashMap<>();
			//			if (1 == invoice.getWhetherMerge()) {
			//				data.put("flag",2);
			//				data.put("username", invoice.getNameOfPartyB());
			//			} else {
			CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(
					Condition.create().eq("crowdsourceid", invoice.getCrowdsourceid()));
			//乙方名字
			String username = crowdsourceAccount.getRealname();
			//乙方身份证图片
			CrowdsourceFile positive = new CrowdsourceFile().selectOne(
					Condition.create().eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()).eq("file_type", 1));
			CrowdsourceFile otherSide = new CrowdsourceFile().selectOne(
					Condition.create().eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()).eq("file_type", 2));
			File filePositive = new File(uploadPathConfig.getUploadpath() + positive.getFilePath());
			File fileOtherSide = new File(uploadPathConfig.getUploadpath() + otherSide.getFilePath());
			data.put("positive", ImgBase64Util.ImgToBase64(filePositive.getAbsolutePath()));
			data.put("otherSide", ImgBase64Util.ImgToBase64(fileOtherSide.getAbsolutePath()));
			data.put("username", username);
			data.put("flag", 1);
			//			}
			data.put("compname", compname);
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("projectServiceName", invoice.getProjectServiceName());
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			data.put("serviceCharge", serviceCharge);
			data.put("entrustedOperator", invoice.getEntrustedOperator());
			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getForeignContractTemplateName(), docConfig.getForeignContract() + folderName,
						contractDocName);
				System.out.println("生成的合同路径为：" + docConfig.getForeignContract() + folderName + File.separator + contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return contractDocFile;
	}

	/**
	 * 下载成本发票开票合同
	 *
	 * @param response  d
	 * @param invoiceId 发票id
	 */
	public void downloadCostInvoiceContract(HttpServletResponse response, int invoiceId) {

		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectById(invoiceId);
		if (null == crowdsourceInvoice) {
			returnResponse(response, StatusMsg.StatusMsg_617);
			return;
		}
		//项目明细
		CrowdsourceProjectItem crowdsourceProjectItem = new CrowdsourceProjectItem().selectOne(
				Condition.create().eq("projectid", crowdsourceInvoice.getProjectid()).eq("userid", crowdsourceInvoice.getCrowdsourceid()));
		if (null == crowdsourceProjectItem || null == crowdsourceProjectItem.getUserType()) {
			returnResponse(response, StatusMsg.StatusMsg_610);
			return;
		}
		CrowdsourceAccount crowdsourceAccount = null;
		MakerAccount makerAccount = null;

		if (1 == crowdsourceProjectItem.getUserType()) {
			//自然人
			crowdsourceAccount = new CrowdsourceAccount().selectOne(
					Condition.create().eq("crowdsourceid", crowdsourceProjectItem.getUserid()));
			if (null == crowdsourceAccount) {
				returnResponse(response, StatusMsg.StatusMsg_626);
				return;
			}
		} else {
			makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", crowdsourceProjectItem.getUserid()));
			if (null == makerAccount) {
				returnResponse(response, StatusMsg.StatusMsg_628);
				return;
			}
		}
		//取到成本发票申请开票时选择的甲方信息
		CrowdsourceCompanyParty crowdsourceCompanyParty = new CrowdsourceCompanyParty().selectById(crowdsourceInvoice.getPartyId());
		if (null == crowdsourceCompanyParty) {
			returnResponse(response, StatusMsg.StatusMsg_637);
			return;
		}
		File contractDocFile = getCostInvoiceContractFile(crowdsourceInvoice, response, crowdsourceProjectItem, crowdsourceAccount,
				makerAccount, crowdsourceCompanyParty);
		if (contractDocFile == null) {
			returnResponse(response, StatusMsg.StatusMsg_199);
			return;
		}
		try {
			downloadFile(response, contractDocFile);
		} catch (Exception e) {
			e.printStackTrace();
			returnResponse(response, optFailSmartResult());
		}

	}

	/**
	 * 生成成本发票开票合同
	 *
	 * @param crowdsourceInvoice 成本发票
	 * @param response           response
	 * @return File
	 */
	private File getCostInvoiceContractFile(CrowdsourceInvoice crowdsourceInvoice, HttpServletResponse response,
											CrowdsourceProjectItem crowdsourceProjectItem, CrowdsourceAccount crowdsourceAccount,
											MakerAccount makerAccount, CrowdsourceCompanyParty crowdsourceCompanyParty) {
		//日期
		Date contractDate = crowdsourceInvoice.getCreatetime();
		//项目金额
		BigDecimal serviceCharge = crowdsourceInvoice.getProjectAmount().setScale(2, RoundingMode.DOWN);
		String contractDocName;

		if (1 == crowdsourceProjectItem.getUserType()) {
			//自然人
			contractDocName =
					crowdsourceInvoice.getId() + "-" + crowdsourceAccount.getRealname() + "-" + crowdsourceInvoice.getProjectAmount() +
							".doc";
			LogUtil.info("即将生成合同:" + contractDocName);
			return getCostInvoiceContractFile(response, crowdsourceInvoice, null, crowdsourceAccount, contractDocName, contractDate,
					serviceCharge, crowdsourceCompanyParty);
		} else {
			//创客
			contractDocName =
					crowdsourceInvoice.getId() + "-" + makerAccount.getRealname() + "-" + crowdsourceInvoice.getProjectAmount() + ".doc";
			LogUtil.info("即将生成合同:" + contractDocName);
			return getCostInvoiceContractFile(response, crowdsourceInvoice, makerAccount, null, contractDocName, contractDate,
					serviceCharge, crowdsourceCompanyParty);
		}
	}

	/**
	 * 生成成本发票开票合同
	 *
	 * @param response           输出
	 * @param crowdsourceInvoice 发票信息
	 * @param makerAccount       创客信息
	 * @param crowdsourceAccount 自然人信息
	 * @param contractDocName    名称
	 * @param contractDate       日期
	 * @param serviceCharge      金额
	 * @return file
	 */
	private File getCostInvoiceContractFile(HttpServletResponse response, CrowdsourceInvoice crowdsourceInvoice, MakerAccount makerAccount,
											CrowdsourceAccount crowdsourceAccount, String contractDocName, Date contractDate,
											BigDecimal serviceCharge, CrowdsourceCompanyParty crowdsourceCompanyParty) {

		//取到成本发票申请开票时选择的甲方信息
		String compname = crowdsourceCompanyParty.getCompanyName();
		String format = "yyyyMMdd";
		//文件夹名称
		String folderName = "/" + DateUtil.DateToStr(format, new Date());
		//创建文件夹 costInvoiceContract
		File filePath = new File(docConfig.getCostInvoiceContract() + folderName);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		File contractDocFile = new File(filePath, contractDocName);

		if (!contractDocFile.exists()) {
			File sealPath = new File(docConfig.getSealPath());
			String compseal = compname + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			//检查甲方企业电子章是否生成
			if (!compsealFile.exists()) {
				//生成电子章
				boolean create = SealUtil.createSimpleCircleSeal(compname, compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(0).minusDays(-30);
			Date endDate = DateUtil.localDate2Date(localDate);

			Map<String, Object> data = new HashMap<>();
			if (null != makerAccount) {
				//创客
				//乙方名字
				String username = makerAccount.getRealname();
				data.put("username", username);
				File filePositive = new File(uploadPathConfig.getUploadpath() + makerAccount.getIdfrontimg());
				File fileOtherSide = new File(uploadPathConfig.getUploadpath() + makerAccount.getIdbackimg());
				data.put("positive", ImgBase64Util.ImgToBase64(filePositive.getAbsolutePath()));
				data.put("otherSide", ImgBase64Util.ImgToBase64(fileOtherSide.getAbsolutePath()));
			} else {
				//自然人
				//乙方名字
				String username = crowdsourceAccount.getRealname();
				data.put("username", username);
				//乙方身份证图片
				CrowdsourceFile positive = new CrowdsourceFile().selectOne(
						Condition.create().eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()).eq("file_type", 1));
				CrowdsourceFile otherSide = new CrowdsourceFile().selectOne(
						Condition.create().eq("crowdsourceid", crowdsourceAccount.getCrowdsourceid()).eq("file_type", 2));
				File filePositive = new File(uploadPathConfig.getUploadpath() + positive.getFilePath());
				File fileOtherSide = new File(uploadPathConfig.getUploadpath() + otherSide.getFilePath());
				data.put("positive", ImgBase64Util.ImgToBase64(filePositive.getAbsolutePath()));
				data.put("otherSide", ImgBase64Util.ImgToBase64(fileOtherSide.getAbsolutePath()));
			}
			data.put("flag", 1);
			//甲方信息
			data.put("compname", compname);

			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			//起始日期
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			//项目服务名称
			data.put("projectServiceName", crowdsourceInvoice.getProjectServiceName());
			//甲方电子章
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			//项目金额
			data.put("serviceCharge", serviceCharge);
			//运营方
			data.put("entrustedOperator", crowdsourceInvoice.getEntrustedOperator());
			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getXuZhouContractTemplateName(), docConfig.getCostInvoiceContract() + folderName,
						contractDocName);
				System.out.println("生成的合同路径为：" + docConfig.getCostInvoiceContract() + folderName + File.separator + contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return contractDocFile;
	}

	/*
	 * @param ips  输入流
	 * @param ops  输出流
	 * @param closeStream  是否关闭流
	 * @throws Exception
	 */
	private static void copyStream(InputStream ips, OutputStream ops, boolean closeStream) throws Exception {
		byte[] buf = new byte[1024];
		int len = ips.read(buf);
		while (len != -1) {
			ops.write(buf, 0, len);
			len = ips.read(buf);
		}
	}

	public static void main(String[] args) throws Exception {
		DocService docService = new DocService();

		Date contractDate = new Date();
		LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
		Date endDate = DateUtil.localDate2Date(localDate);
		Map<String, Object> data = new HashMap<>();
		String s = ImgBase64Util.ImgToBase64("C:\\ZDD\\32a383b24ae903d7e0e4000c8789ea5.png");
		data.put("compname", "苍穹苍穹苍穹苍穹苍穹科技有限公司");
		data.put("username", "dididi");

		data.put("usernameAutograph", "");
		data.put("serviceCharge", NumberUtil.formatFloat2_0(4000));
		data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
		data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
		data.put("startMonth", DateUtil.getString(contractDate, "MM"));
		data.put("startDay", DateUtil.getString(contractDate, "dd"));
		data.put("endYear", DateUtil.getString(endDate, "yyyy"));
		data.put("endMonth", DateUtil.getString(endDate, "MM"));
		data.put("endDay", DateUtil.getString(endDate, "dd"));
		String compseal = ImgBase64Util.ImgToBase64("C:\\ZDD\\上海信栖网络科技有限公司_seal.png");
		String userseal = ImgBase64Util.ImgToBase64("C:\\ZDD\\上海信栖网络科技有限公司_seal.png");
		data.put("compseal", compseal);
		data.put("userseal", userseal);
		data.put("content", "content");
		data.put("projectname", "content");
		String templateName = "contract_template.ftl";
		String path = "D:\\Desktop";
		WordUtil.createWord(data, templateName, path, "12134.doc");
		/*try {
			docService.generateContract(new File("/Users/neyxixi/Downloads/Bob/项目文档/ /contractdoc/123.docx"), data);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
	}

	/**
	 * 下载众包项目合同附件
	 *
	 * @param response  response
	 * @param projectid projectid
	 */
	public void downloadProjectAttachment(HttpServletResponse response, int projectid) throws IOException {

		//获取众包附件所需信息
		List<ProjectAttachmentDto> dtoList = crowdsourceProjectItemMapper.projectAttachmentDetail(projectid);
		if (null != dtoList && dtoList.size() > 0) {
			//新建一个临时文件夹，将后续生成的所有文件 都放在这个文件夹下
			String temporaryFolderName = "projectTemporaryFolder" + System.currentTimeMillis();
			File temporaryFolderFile = new File(uploadPathConfig.getUserLocal() + temporaryFolderName);
			if (!temporaryFolderFile.exists()) {
				if (!temporaryFolderFile.mkdirs()) {
					com.info.zhiduoduo.wxsdk.utils.LogUtil.error("生成众包项目合同附件压缩包-新建临时文件夹失败！");
					return;
				}
			}
			for (ProjectAttachmentDto projectAttachmentDto : dtoList) {
				File projectAttachmentFile = getProjectAttachmentFile(response, temporaryFolderName, projectAttachmentDto);
				if (null == projectAttachmentFile) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					LogUtil.info("生成众包项目附件 失败！");
					return;
				}
			}
			//第一种方法：
			OutputStream out = response.getOutputStream();
			try {
				// 调用方法打包zip文件
				byte[] data = FileUtil.createZip(temporaryFolderFile.getPath());
				// 压缩包名称
				String downloadName =
						DateUtil.DateToStr("yyyy-MM-dd", dtoList.get(0).getFinishtime()) + "-" + dtoList.get(0).getProjectName() + ".zip";
				response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "utf-8"));
				response.addHeader("Content-Length", "" + data.length);
				response.setContentType("application/octet-stream;charset=UTF-8");
				IOUtils.write(data, out);
			} catch (Exception e) {
				com.info.zhiduoduo.wxsdk.utils.LogUtil.error("将文件夹压缩为压缩包失败！");
			} finally {
				try {
					// 压缩成功后删除项目中文件夹
					if (temporaryFolderFile.exists()) {
						FileUtil.delFiles(temporaryFolderFile);
					}
					if (out != null) {
						out.flush();
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
					com.info.zhiduoduo.wxsdk.utils.LogUtil.error("下载众包项目附件文件-将文件夹压缩为压缩包");
				}
			}
		}

	}

	/**
	 * 生成众包项目合同附件
	 *
	 * @param response             response
	 * @param temporaryFolderName  文件夹
	 * @param projectAttachmentDto 合同所需信息
	 * @return file
	 */
	private File getProjectAttachmentFile(HttpServletResponse response, String temporaryFolderName,
										  ProjectAttachmentDto projectAttachmentDto) {

		String contractDocName = projectAttachmentDto.getUserName() + "-" + projectAttachmentDto.getUserid() + ".doc";
		File projectAttachmentFile = new File(uploadPathConfig.getUserLocal() + temporaryFolderName, contractDocName);
		if (!projectAttachmentFile.exists()) {
			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			String seal = projectAttachmentDto.getStudioName() + "_seal.png";
			File studioseal = new File(sealPath, seal);
			if (!studioseal.exists()) {
				if (projectAttachmentDto.getStudioName() == null) {
					return null;
				}
				boolean create = SealUtil.createSimpleCircleSeal(projectAttachmentDto.getStudioName(), studioseal.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}

			Map<String, Object> data = new HashMap<>();
			if (2 == projectAttachmentDto.getUserType()) {
				//个体户需要工作室的章
				data.put("flag", 1);
				data.put("studioseal", ImgBase64Util.ImgToBase64(studioseal.getAbsolutePath()));
			} else {
				data.put("flag", 2);
			}
			data.put("compname", projectAttachmentDto.getCompname());
			data.put("companyLegalPerson", projectAttachmentDto.getCompanyLegalPerson());
			data.put("companyPhone", projectAttachmentDto.getCompanyPhone());
			data.put("companyEmail", projectAttachmentDto.getCompanyEmail());
			data.put("studioName", projectAttachmentDto.getStudioName());
			data.put("userName", projectAttachmentDto.getUserName());
			data.put("userPhone", projectAttachmentDto.getUserPhone());
			data.put("userEmail", projectAttachmentDto.getUserEmail());
			data.put("projectName", projectAttachmentDto.getProjectName());
			data.put("projectAmount", projectAttachmentDto.getProjectAmount());
			data.put("projectServiceCharge", projectAttachmentDto.getProjectServiceCharge());
			data.put("amountInWords", NumberToCN.toChinese(projectAttachmentDto.getSumAmount().toString()));
			data.put("sumAmount", projectAttachmentDto.getSumAmount());
			data.put("finishTime", DateUtil.getString(projectAttachmentDto.getFinishtime(), DateUtil.FORMAT_STYLE_3));
			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getProjectAttachmentTemplate(), uploadPathConfig.getUserLocal() + temporaryFolderName,
						contractDocName);
				System.out.println(
						"生成的附件临时路径为：" + uploadPathConfig.getUserLocal() + temporaryFolderName + File.separator + contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return projectAttachmentFile;
	}

	/**
	 * 生成 模板文件
	 *
	 * @param response
	 * @param temporaryFolderName 临时文件夹名称
	 * @param dataDto             填充数据
	 * @return
	 */
	private File generateTemplateFile(HttpServletResponse response, String temporaryFolderName, ProjectContractDataDto dataDto) {

		DecimalFormat df = new DecimalFormat("##,##0.00");

		// 项目名称
		String contractDocName =
				dataDto.getProjectName() + "-" + DateUtil.getStringDate(dataDto.getProjectCreateTime(), DateUtil.FORMAT_STYLE_7) + ".doc";
		// 文件路径
		File projectContractFile = new File(uploadPathConfig.getUserLocal() + temporaryFolderName, contractDocName);
		if (!projectContractFile.exists()) {
			Map<String, Object> data = new HashMap<>();
			// 甲方信息
			data.put("compname", dataDto.getCompname()); //甲方公司
			data.put("companyLegalPerson", dataDto.getCompanyLegalPerson()); //甲方联系人
			data.put("companyPhone", dataDto.getCompanyPhone()); //甲方联系电话
			// data.put("companyAddress", dataDto.getCompanyAddress());

			data.put("projectName", dataDto.getProjectName()); //项目名称
			data.put("projectTotalAmount", df.format(dataDto.getProjectTotalAmount())); //项目金额
			data.put("moneyChinese", NumberToCN.toChinese(dataDto.getProjectTotalAmount().toString())); // 人民币大写

			data.put("manager", dataDto.getManager()); // 商务经理

			// 共享经济众包项目 实施时间
			data.put("starYear", DateUtil.getString(dataDto.getProjectCreateTime(), "yyyy"));
			data.put("starMonth", DateUtil.getString(dataDto.getProjectCreateTime(), "MM"));
			data.put("starDay", DateUtil.getString(dataDto.getProjectCreateTime(), "dd"));
			data.put("endYear", DateUtil.getString(dataDto.getFinishtime(), "yyyy"));
			data.put("endMonth", DateUtil.getString(dataDto.getFinishtime(), "MM"));
			data.put("endDay", DateUtil.getString(dataDto.getFinishtime(), "dd"));

			String templateName = "";
			if (1 == dataDto.getCrowdsourceType()) {
				//代付模式
				templateName = docConfig.getAcceptPaymentModeTemplate();
			} else if (2 == dataDto.getCrowdsourceType()) {
				//承揽模式
				templateName = docConfig.getAcceptContractModeTemplate();

				// 承揽模式下 乙方的信息
				data.put("userName", dataDto.getUserName());
				if (dataDto.getStudioName() == null) {
					return null;
				}
				data.put("studioName", dataDto.getStudioName());
				data.put("userPhone", dataDto.getUserPhone());

			} else {
				// 目前 企业只有承揽模式和 代付模式 出现其他不做操作
				return null;
			}
			try {
				//使用freemarker 生成验收合同模板
				WordUtil.createWord(data, templateName, uploadPathConfig.getUserLocal() + temporaryFolderName, contractDocName);
				System.out.println(
						"生成的众包项目 验收合同模板 临时路径为：" + uploadPathConfig.getUserLocal() + temporaryFolderName + File.separator + contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return projectContractFile;

	}

	/**
	 * 下载  项目 验收模板
	 *
	 * @param response
	 * @param projectIdList
	 */
	public void downloadZhiDuoDuoProjectTemplate(HttpServletResponse response, List<Integer> projectIdList) throws IOException {

		if (projectIdList == null || projectIdList.size() <= 0) return;
		ArrayList<ProjectContractDataDto> infoList = new ArrayList<>();
		for (Integer projectId : projectIdList) {
			ProjectContractDataDto dataDto = new ProjectContractDataDto();
			dataDto.setProjectId(projectId);
			buildZhiDuoDuoTemplateData(dataDto, response, projectId);
			infoList.add(dataDto);
		}

		if (!CollectionUtils.isEmpty(infoList)) {
			//新建一个临时文件夹，将后续生成的所有文件 都放在这个文件夹下
			String temporaryFolderName = "projectFileTemporaryFolder" + System.currentTimeMillis();
			File temporaryFolder = new File(uploadPathConfig.getUserLocal() + temporaryFolderName);
			log.info(uploadPathConfig.getUserLocal() + temporaryFolderName + "===========================");
			if (!temporaryFolder.exists()) {
				if (!temporaryFolder.mkdirs()) {
					LogUtil.error("下载 项目验收模板-新建临时文件夹失败！");
					return;
				}
			}

			// 生成文件
			for (ProjectContractDataDto projectContractDataDto : infoList) {
				File projectModelFile = generateZhiDuoDuoTemplateFile(response, temporaryFolderName, projectContractDataDto);
				if (null == projectModelFile) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					LogUtil.error("生成 项目验收模板！失败的项目id为:" + projectContractDataDto.getProjectId());
					return;
				}
			}
			//第一种方法：
			OutputStream out = response.getOutputStream();
			try {
				// 调用方法打包zip文件
				byte[] zip = FileUtil.createZip(temporaryFolder.getPath());
				// 压缩包名称
				String zipName = " 项目验收模板" + "-" + DateUtil.DateToStr("yyyy-MM-dd", new Date()) + ".zip";
				response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "utf-8"));
				response.addHeader("Content-Length", "" + zip.length);
				response.setContentType("application/octet-stream;charset=UTF-8");
				IOUtils.write(zip, out);
			} catch (Exception e) {
				LogUtil.error(" 项目验收模板-项目文件夹压缩为压缩包失败！");
			} finally {
				try {
					// 压缩成功后删除之前的临时文件夹
					if (temporaryFolder.exists()) {
						FileUtil.delFiles(temporaryFolder);
					}
					//关闭流
					if (out != null) {
						out.flush();
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
					LogUtil.error(" 项目验收模板-将文件夹压缩为压缩包错误！");
				}
			}
		}

	}

	/**
	 * 生成  项目 验收模板
	 *
	 * @param response
	 * @param temporaryFolderName
	 * @param dataDto
	 * @return
	 */
	private File generateZhiDuoDuoTemplateFile(HttpServletResponse response, String temporaryFolderName, ProjectContractDataDto dataDto) {

		DecimalFormat df = new DecimalFormat("##,##0.00");
		// 项目名称
		String contractDocName =
				dataDto.getProjectName() + "-" + DateUtil.getStringDate(dataDto.getProjectCreateTime(), DateUtil.FORMAT_STYLE_7) + ".doc";
		// 文件路径
		File projectContractFile = new File(uploadPathConfig.getUserLocal() + temporaryFolderName, contractDocName);
		if (!projectContractFile.exists()) {
			Map<String, Object> data = new HashMap<>();

			data.put("manager", dataDto.getManager()); // 商务经理

			data.put("projectName", dataDto.getProjectName()); //项目名称
			data.put("projectTotalAmount", df.format(dataDto.getProjectTotalAmount())); //项目金额
			data.put("moneyChinese", NumberToCN.toChinese(dataDto.getProjectTotalAmount().toString())); // 人民币大写

			// 共享经济众包项目 实施时间
			data.put("endYear", DateUtil.getString(dataDto.getFinishtime(), "yyyy"));
			data.put("endMonth", DateUtil.getString(dataDto.getFinishtime(), "MM"));
			data.put("endDay", DateUtil.getString(dataDto.getFinishtime(), "dd"));
			data.put("starYear", DateUtil.getString(dataDto.getProjectCreateTime(), "yyyy"));
			data.put("starMonth", DateUtil.getString(dataDto.getProjectCreateTime(), "MM"));
			data.put("starDay", DateUtil.getString(dataDto.getProjectCreateTime(), "dd"));

			// 甲方信息
			data.put("compname", dataDto.getCompname()); //甲方公司
			data.put("companyLegalPerson", dataDto.getCompanyLegalPerson()); //甲方联系人
			data.put("companyPhone", dataDto.getCompanyPhone()); //甲方联系电话

			data.put("studioName", dataDto.getStudioName()); // 工作室

			//   模板名
			String templateName = docConfig.getZddAcceptProjectTemplate();

			try {
				//使用freemarker 生成验收合同模板
				WordUtil.createWord(data, templateName, uploadPathConfig.getUserLocal() + temporaryFolderName, contractDocName);
				System.out.println("生成的 项目 验收合同模板 临时路径为：" + uploadPathConfig.getUserLocal() + temporaryFolderName + File.separator +
						contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return projectContractFile;
	}

	/**
	 * 构建   项目数据
	 *
	 * @param dataDto
	 * @param response
	 * @param projectId
	 */
	private void buildZhiDuoDuoTemplateData(ProjectContractDataDto dataDto, HttpServletResponse response, Integer projectId) {

		// 获取  项目信息
		CompanyProject companyProject = new CompanyProject().selectById(projectId);

		if (null == companyProject) {
			returnResponse(response, StatusMsg.StatusMsg_301);
			return;
		}

		// 设置信息
		dataDto.setProjectName(companyProject.getProjectname())
			   .setProjectTotalAmount(companyProject.getProjectamount())
			   .setProjectCreateTime(companyProject.getProjectstart())
			   .setFinishtime(companyProject.getProjectfinish());

		Company company = new Company().selectById(companyProject.getCompid());

		if (null == company) {
			returnResponse(response, StatusMsg.StatusMsg_302);
			return;
		}

		//获取企业详细信息
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
		if (null == companyAccount) {
			returnResponse(response, StatusMsg.StatusMsg_313);
			return;
		}
		// 设置企业信息
		dataDto.setCompname(company.getCompname())
			   .setCompanyLegalPerson(company.getContactname())
			   .setCompanyPhone(company.getContactphone())
			   .setCompanyAddress(company.getContactaddress());

		// 获取 企业的商务经理
		BusinessManager businessManager = new BusinessManager().selectById(companyAccount.getBusinessManagerId());
		if (businessManager != null) {
			dataDto.setManager(businessManager.getBusinessManager());
		}

		// 获取 创客工作室 信息
		MakerStudio makerStudio = new MakerStudio().selectOne(Condition.create().eq("userid", companyProject.getUserid()));
		if (makerStudio != null) {
			dataDto.setStudioName(makerStudio.getUsername());
		}
	}

	/**
	 * 下载众包项目合同包含所有子项目的zip文件包
	 *
	 * @param response response
	 * @param compids
	 */
	public void downloadCrowdsourceProjectZipFileByCompids(HttpServletResponse response, List<Integer> compids) {

		Asserts.notEmpty(compids);

		// 临时文件夹
		String temporaryFolderName = "projectFileTemporaryFolder" + System.currentTimeMillis();
		String temporaryFolder = uploadPathConfig.getUserLocal() + File.separator + temporaryFolderName;

		List<String> compnames = Lists.newArrayList();
		// 遍历企业，每个企业新建一个文件夹
		for (Integer compid : compids) {
			// 获取企业信息
			Company company = companyMapper.selectById(compid);
			Asserts.notNull(company, StatusMsg.StatusMsg_302);
			compnames.add(company.getCompname());

			// 企业文件夹路径
			String companyFileFolder = temporaryFolder + File.separator + company.getCompname();

			// 获取所有智众包项目
			List<CrowdsourceProject> projectList = crowdsourceProjectMapper.listByCompid(compid);
			for (CrowdsourceProject crowdsourceProject : projectList) {
				// 子项目列表
				List<CrowdsourceProjectItem> itemList = new CrowdsourceProjectItem().selectList(
						Condition.create().eq("projectid", crowdsourceProject.getProjectid()).eq("deleted", 0));
				if (CollectionUtils.isEmpty(itemList)) continue;

				// 获取运营主体
				CrowdsourceCompanyParty party = new CrowdsourceCompanyParty().selectById(crowdsourceProject.getPartyId());

				// 合同存放路径
				String projectFileFolder =
						companyFileFolder + File.separator + crowdsourceProject.getProjectid() + "-" + crowdsourceProject.getProjectName();
				String fileFolderPath = generateCrowdsourceContractFolder(crowdsourceProject);
				// 对每个子项目生成合同文件，并存入文件夹
				for (CrowdsourceProjectItem item : itemList) {
					CrowdsourceContractDto dto = CrowdsourceContractDto.of(company, party, crowdsourceProject, item);
					// 生成合同文件，保存在特定的文件夹里面。
					File file = generateCrowdsourceContractFileInteral(response, dto, fileFolderPath);

					// 将生成的合同文件复制到临时文件夹
					try {
						org.apache.commons.io.FileUtils.copyFile(file, new File(projectFileFolder, file.getName()));
					} catch (IOException e) {
						log.error("复制文件报错，文件路径：{}", file.getAbsolutePath(), e);
					}
				}
			}
		}

		// 生成压缩包
		try (OutputStream out = response.getOutputStream()) {
			// 压缩包名称
			String zipName = StringUtils.join(compnames, "+") + ".zip";
			// 调用方法打包zip文件
			FileUtil.createZip2Response(response, temporaryFolder, zipName);
		} catch (Exception e) {
			log.error("将众包项目文件夹压缩为压缩包失败！", e);
		} finally {
			// 删除临时文件夹
			FileUtil.deleteDir(temporaryFolder);
		}
	}

	/**
	 * 下载众包项目合同包含所有子项目的zip文件包
	 *
	 * @param response  response
	 * @param projectid projectid
	 */
	public void downloadCrowdsourceProjectZipFile(HttpServletResponse response, int projectid) {

		// 获取项目信息
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectid);
		Asserts.notNull(crowdsourceProject, StatusMsg.StatusMsg_301);

		// 子项目列表
		List<CrowdsourceProjectItem> itemList = new CrowdsourceProjectItem().selectList(
				Condition.create().eq("projectid", projectid).eq("deleted", 0));
		Asserts.notEmpty(itemList, StatusMsg.StatusMsg_610);

		// 获取企业信息
		Company company = companyMapper.selectById(crowdsourceProject.getCompid());
		Asserts.notNull(company, StatusMsg.StatusMsg_302);

		// 获取运营主体
		CrowdsourceCompanyParty party = new CrowdsourceCompanyParty().selectById(crowdsourceProject.getPartyId());

		// 合同存放路径
		String fileFolderPath = generateCrowdsourceContractFolder(crowdsourceProject);

		// 对每个子项目生成合同文件，并存入文件夹
		List<File> contractList = Lists.newArrayList();
		for (CrowdsourceProjectItem item : itemList) {
			CrowdsourceContractDto dto = CrowdsourceContractDto.of(company, party, crowdsourceProject, item);
			contractList.add(generateCrowdsourceContractFileInteral(response, dto, fileFolderPath));
		}

		// 生成压缩包
		Asserts.notEmpty(contractList, StatusMsg.StatusMsg_650);
		try (OutputStream out = response.getOutputStream()) {
			// 压缩包名称
			String zipName = company.getCompname() + "-" + DateUtil.DateToStr("yyyy-MM-dd", crowdsourceProject.getFinishtime()) + "-" +
					crowdsourceProject.getProjectName() + ".zip";
			// 调用方法打包zip文件
			FileUtil.createZip2Response(response, fileFolderPath, zipName);
		} catch (Exception e) {
			log.error("将众包项目文件夹压缩为压缩包失败！", e);
		}
	}

	public void downloadCrowdsourceProjectItemDocFile(HttpServletResponse response, int projectItemId) {

		// 子项目
		CrowdsourceProjectItem projectItem = new CrowdsourceProjectItem().selectById(projectItemId);
		Asserts.notNull(projectItem, StatusMsg.StatusMsg_610);

		// 获取项目信息
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectItem.getProjectid());
		Asserts.notNull(crowdsourceProject, StatusMsg.StatusMsg_301);

		// 获取企业信息
		Company company = companyMapper.selectById(crowdsourceProject.getCompid());
		Asserts.notNull(company, StatusMsg.StatusMsg_302);

		// 获取运营主体
		CrowdsourceCompanyParty party = new CrowdsourceCompanyParty().selectById(crowdsourceProject.getPartyId());

		// 合同存放路径
		String fileFolderPath = generateCrowdsourceContractFolder(crowdsourceProject);

		CrowdsourceContractDto dto = CrowdsourceContractDto.of(company, party, crowdsourceProject, projectItem);
		File contractFile = generateCrowdsourceContractFileInteral(response, dto, fileFolderPath);
		if (null == contractFile) {
			returnResponse(response, StatusMsg.StatusMsg_199);
			LogUtil.info("生成众包项目合同 失败！");
			return;
		}

		//contract doc exists, download
		try {
			downloadFile(response, contractFile);
		} catch (Exception e) {
			log.error("downloadCrowdsourceProjectItemDocFile", e);
			returnResponse(response, optFailSmartResult());
		}
	}

	private File generateCrowdsourceContractFileInteral(HttpServletResponse response, CrowdsourceContractDto dto, String fileFolderPath) {
		BigDecimal serviceCharge = dto.getProjectAmount().setScale(2, BigDecimal.ROUND_HALF_UP);

		String contractNo = "ZZB" + DateUtil.getString(dto.getProjectCreateTime(), DateUtil.FORMAT_STYLE_5) + dto.getId();
		String name = StringUtils.isEmpty(dto.getStudioName()) ? dto.getUserName() : dto.getStudioName();
		String contractDocName = name + "-" + dto.getUserid() + "-" + dto.getId() + ".doc";
		// 此处使用企业主体名称partyName
		String companyName = StringUtils.defaultString(dto.getPartyName());
		String username = dto.getUserType() == CrowdsourceUserType.NATURAL_PERSON ? dto.getUserName() : dto.getStudioName();

		return generateCrowdsourceDocFileInternal(response, contractDocName, contractNo, companyName, dto.getUserType(), username,
				dto.getProjectCreateTime(), dto.getProjectName(), dto.getProjectDesc(), serviceCharge, fileFolderPath);
	}

	/**
	 * 下载众包项目合同包含所有子项目的zip文件包
	 *
	 * @param response      response
	 * @param entrusteeList
	 */
	public void downloadProjectEntrusteeContractZipFile(HttpServletResponse response, EntrustmentProject entrustmentProject,
														List<ProjectEntrusteeInfoDto> entrusteeList) {

		// 获取企业信息
		Company company = companyMapper.selectById(entrustmentProject.getCompid());
		Asserts.notNull(company, StatusMsg.StatusMsg_302);

		// 合同存放路径
		String fileFolderPath = generateEntrustContractFolder(entrustmentProject);

		// 对每个子项目生成合同文件，并存入文件夹
		List<File> contractList = Lists.newArrayList();
		for (ProjectEntrusteeInfoDto dto : entrusteeList) {
			contractList.add(generateEntrustContractFileInteral(response, dto, fileFolderPath));
		}

		// 生成压缩包
		Asserts.notEmpty(contractList, StatusMsg.StatusMsg_650);
		try (OutputStream out = response.getOutputStream()) {
			// 压缩包名称
			String zipName = company.getCompname() + "-" + DateUtil.DateToStr("yyyy-MM-dd", entrustmentProject.getCreatetime()) + "-" +
					entrustmentProject.getOriginFileName() + ".zip";
			// 调用方法打包zip文件
			FileUtil.createZip2Response(response, fileFolderPath, zipName);
		} catch (Exception e) {
			log.error("将众包项目文件夹压缩为压缩包失败！", e);
		}
	}

	/**
	 * 下载 项目合同包含所有子项目的zip文件包
	 *
	 * @param response      response
	 * @param entrusteeList
	 */
	public void zddDownloadProjectEntrusteeContractZipFile(HttpServletResponse response, EntrustmentProject entrustmentProject,
														List<ProjectEntrusteeInfoDto> entrusteeList) {

		// 获取企业信息
		Company company = companyMapper.selectById(entrustmentProject.getCompid());
		Asserts.notNull(company, StatusMsg.StatusMsg_302);

		// 合同存放路径
		String fileFolderPath = generateEntrustContractFolder(entrustmentProject);

		// 对每个子项目生成合同文件，并存入文件夹
		List<File> contractList = Lists.newArrayList();
		for (ProjectEntrusteeInfoDto dto : entrusteeList) {
			contractList.add(zddGenerateEntrustContractFileInteral(response, dto, fileFolderPath));
		}

		// 生成压缩包
		Asserts.notEmpty(contractList, StatusMsg.StatusMsg_650);
		try (OutputStream out = response.getOutputStream()) {
			// 压缩包名称
			String zipName = company.getCompname() + "-" + DateUtil.DateToStr("yyyy-MM-dd", entrustmentProject.getCreatetime()) + "-" +
					entrustmentProject.getOriginFileName() + ".zip";
			// 调用方法打包zip文件
			FileUtil.createZip2Response(response, fileFolderPath, zipName);
		} catch (Exception e) {
			log.error("将众包项目文件夹压缩为压缩包失败！", e);
		}
	}
	public void downloadProjectEntrusteeContractFile(HttpServletResponse response, EntrustmentProject entrustmentProject,
													 ProjectEntrusteeInfoDto infoDto) {

		// 合同存放路径
		String fileFolderPath = generateEntrustContractFolder(entrustmentProject);

		File contractFile = generateEntrustContractFileInteral(response, infoDto, fileFolderPath);
		if (null == contractFile) {
			returnResponse(response, StatusMsg.StatusMsg_199);
			LogUtil.info("生成众包项目合同 失败！");
			return;
		}

		//contract doc exists, download
		try {
			downloadFile(response, contractFile);
		} catch (Exception e) {
			log.error("downloadCrowdsourceProjectItemDocFile", e);
			returnResponse(response, optFailSmartResult());
		}
	}

	private File generateEntrustContractFileInteral(HttpServletResponse response, ProjectEntrusteeInfoDto dto, String fileFolderPath) {
		Asserts.notNull(dto, StatusMsg.StatusMsg_1110);

		String contractNo =
				"WT" + DateUtil.getString(dto.getCreatetime(), DateUtil.FORMAT_STYLE_5) + dto.getImportId() + dto.getEntrusteeId();
		String contractDocName = dto.getEntrusteeStudio() + "-" + dto.getEntrusteeId() + ".doc";

		BigDecimal serviceCharge = BigDecimal.ZERO;
		String companyName = "";
		if (NumberUtil.equals(dto.getProjectType(), ProjectType.ENTRUST_CROWDSOURCE)) {
			// 委托众包项目，使用主体企业名称
			companyName = dto.getPrincipalName();
			serviceCharge = dto.getProjectAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
		} else {
			companyName = dto.getCompname();
			// 委托接单使用含税金额
			serviceCharge = dto.getTaxInclusiveAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
		}
		String username = dto.getEntrusteeStudio();

		return generateCrowdsourceDocFileInternal(response, contractDocName, contractNo, companyName, CrowdsourceUserType.STUDIO, username,
				dto.getCreatetime(), dto.getName(), dto.getContent(), serviceCharge, fileFolderPath);
	}
	private File zddGenerateEntrustContractFileInteral(HttpServletResponse response, ProjectEntrusteeInfoDto dto, String fileFolderPath) {
		Asserts.notNull(dto, StatusMsg.StatusMsg_1110);

		String contractNo =
				"WT" + DateUtil.getString(dto.getCreatetime(), DateUtil.FORMAT_STYLE_5) + dto.getImportId() + dto.getEntrusteeId();
		String contractDocName = dto.getEntrusteeStudio() + "-" + dto.getEntrusteeId() + ".doc";

		BigDecimal serviceCharge = BigDecimal.ZERO;
		String companyName = "";
		if (NumberUtil.equals(dto.getProjectType(), ProjectType.ENTRUST_CROWDSOURCE)) {
			// 委托众包项目，使用主体企业名称
			companyName = dto.getPrincipalName();
			serviceCharge = dto.getProjectAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
		} else {
			companyName = dto.getCompname();
			// 委托接单使用含税金额
			serviceCharge = dto.getTaxInclusiveAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
		}
		String username = dto.getEntrusteeStudio();

		return moreThanMoreContractTemplate(response, contractDocName, contractNo, companyName, CrowdsourceUserType.STUDIO, username,
				dto.getCreatetime(), dto.getName(), dto.getContent(), serviceCharge, fileFolderPath,dto.getPrincipalName());
	}

	private String generateEntrustContractFolder(EntrustmentProject project) {
		return StringUtils.joinWith(File.separator, docConfig.getEntrusteeDocFilePath(),
				DateUtil.getString(project.getCreatetime(), DateUtil.FORMAT_STYLE_5), project.getId());
	}

	private String generateCrowdsourceContractFolder(CrowdsourceProject project) {
		return StringUtils.joinWith(File.separator, docConfig.getCrowdsourceDocFilePath(),
				DateUtil.getString(project.getCreatetime(), DateUtil.FORMAT_STYLE_5), project.getProjectid());
	}

	/**
	 * 用的还是 的创客合同模板
	 *
	 * @return
	 */
	private File generateCrowdsourceDocFileInternal(HttpServletResponse response, String contractDocName, String contractNo,
													String compname, int userType, String username, Date contractDate, String projectname,
													String projectContent, BigDecimal serviceCharge, String fileFolderPath) {

		File filePath = new File(fileFolderPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		File contractDocFile = new File(filePath, contractDocName);

		if (!contractDocFile.exists()) {
			FileUtils.delete(contractDocFile);

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			if (!sealPath.exists()) {
				sealPath.mkdirs();
			}
			String compseal = compname + "_seal.png";
			String userseal = username + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(compname, compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			File usersealFile = null;
			if (userType == CrowdsourceUserType.STUDIO) {
				usersealFile = new File(sealPath, userseal);
				// 自然人不需要生成章
				if (!usersealFile.exists()) {
					boolean create = SealUtil.createSimpleCircleSeal(username, usersealFile.getAbsolutePath());
					if (!create) {
						returnResponse(response, StatusMsg.StatusMsg_199);
						return null;
					}
				}
			}
			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
			Date endDate = DateUtil.localDate2Date(localDate);
			Map<String, Object> data = new HashMap<>();
			data.put("contractNo", contractNo);
			// 使用企业主体名称
			data.put("compname", compname);
			data.put("principalName", compname);
			data.put("username", username);
			data.put("serviceCharge", serviceCharge);
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("validity", 1);
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("projectname", projectname);
			data.put("content", projectContent);
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			data.put("userseal", usersealFile == null ? "" : ImgBase64Util.ImgToBase64(usersealFile.getAbsolutePath()));

			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getZddContractTemplate(), filePath.getAbsolutePath(), contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return contractDocFile;
	}
	/**
	 * 新 合同模板
	 *
	 * @return
	 */
	private File moreThanMoreContractTemplate(HttpServletResponse response, String contractDocName, String contractNo,
													String compname, int userType, String username, Date contractDate, String projectname,
													String projectContent, BigDecimal serviceCharge, String fileFolderPath,String principalName) {

		File filePath = new File(fileFolderPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		File contractDocFile = new File(filePath, contractDocName);

		if (!contractDocFile.exists()) {
			FileUtils.delete(contractDocFile);

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			if (!sealPath.exists()) {
				sealPath.mkdirs();
			}
			String compseal = compname + "_seal.png";
			String userseal = username + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(compname, compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			File usersealFile = null;
			if (userType == CrowdsourceUserType.STUDIO) {
				usersealFile = new File(sealPath, userseal);
				// 自然人不需要生成章
				if (!usersealFile.exists()) {
					boolean create = SealUtil.createSimpleCircleSeal(username, usersealFile.getAbsolutePath());
					if (!create) {
						returnResponse(response, StatusMsg.StatusMsg_199);
						return null;
					}
				}
			}
			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
			Date endDate = DateUtil.localDate2Date(localDate);
			Map<String, Object> data = new HashMap<>();
			data.put("contractNo", contractNo);
			// 使用企业主体名称
			data.put("compname", compname);
			data.put("username", username);
			data.put("serviceCharge", serviceCharge);
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("validity", 1);
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("projectname", projectname);
			data.put("content", projectContent);
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			data.put("userseal", usersealFile == null ? "" : ImgBase64Util.ImgToBase64(usersealFile.getAbsolutePath()));
			data.put("principalName",principalName);
			try {
				//使用freemarker 生成合同
				WordUtil.createWord(data, docConfig.getZddContractTemplate(), filePath.getAbsolutePath(), contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return contractDocFile;
	}

	/**
	 * 生成智众包项目交付文档，返回文件
	 *
	 * @param compid
	 * @param projectIds
	 * @param templateType 使用模版 2：智众包双方模版，3：智众包三方模版
	 * @param saveDeliveryPath 是否保存生成到文档路径到众包交付文件字段，只有模版为1的时候有可能保存
	 * @return
	 */
	public List<ExportProjectAcceptanceDto> generateCrowdsourceDocDeliverFile(int compid, String projectIds,int templateType,boolean saveDeliveryPath) {
		String states = CalcAmountType.getCrowdsourceProjectStates(CalcAmountType.FINISHED);
		//获取当前企业下所有已完成的众包项目,交付/验收文件地址为空的项目
		List<ExportProjectAcceptanceDto> list = crowdsourceProjectMapper.getCrowdsourceProjectAcceptance(compid, projectIds, states);
		for (ExportProjectAcceptanceDto dto : list) {
			List<ExportProjectAcceptanceItemDto> itemList = crowdsourceProjectItemMapper.getProjectAcceptanceItemList(dto.getProjectid());
			dto.setList(itemList);

			String filePath = generateCrowdsourceDocDeliverFile(dto, templateType).getPath();
			dto.setDeliveryPath(filePath);

			if (saveDeliveryPath) {
				new CrowdsourceProject().setProjectid(dto.getProjectid()).setDeliveryPath(filePath).updateById();
			}
		}
		return list;
	}

	/**
	 * 生成之众包项目验收文件，
	 * @param dto
	 * @param templateType templateType 使用模版 2：智众包双方模版，3：智众包三方模版
	 * @return
	 */
	public File generateCrowdsourceDocDeliverFile(ExportProjectAcceptanceDto dto,int templateType) {

		String fileFolderPath = docConfig.getDeliverDocFilePath() + File.separator + dto.getCompid() + File.separator + templateType;
		File filePath = new File(fileFolderPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		String zddName = dto.getWorkType() == Constants.WORK_TYPE_1 ? "ZZB" : "ZLG";
		String contractDocName = "《项目验收&结算确认单》_" + dto.getCompname() + "_" + DateUtil.getString(dto.getProjectfinish(), DateUtil.FORMAT_STYLE_5) + "_" + zddName + dto.getProjectid() + ".pdf";
		File contractDocFile = new File(filePath, contractDocName);
		if (!contractDocFile.exists()) {
			FileUtils.delete(contractDocFile);

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			if (!sealPath.exists()) {
				sealPath.mkdirs();
			}
			String compseal = dto.getCompname() + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(dto.getCompname(), compsealFile.getAbsolutePath());
				if (!create) {
					throw SmartException.of(StatusMsg.StatusMsg_199);
				}
			}

			Map<String, Object> data = new HashMap<>();
			data.put("publishTime", DateUtil.getString(dto.getPublishTime(), DateUtil.FORMAT_STYLE_3));
			data.put("generalTime", DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_3));
			data.put("compname", dto.getCompname());
			data.put("partyname", dto.getPartyname());
			data.put("projectname", dto.getProjectname());
			data.put("projectAmount", dto.getProjectAmount());
			data.put("moneyChinese", NumberToCN.toChinese(dto.getProjectAmount().toString()));
			for (ExportProjectAcceptanceItemDto item : dto.getList()) {
				item.setProjectAmountChinese(NumberToCN.toChinese(item.getProjectAmount().toString()));// 人民币大写
				item.setIntegratedTaxFeeChinese(NumberToCN.toChinese(item.getIntegratedTaxFee().toString()));// 人民币大写
			}
			data.put("list", dto.getList());
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));

			try {
				//使用freemarker 生成pdf文件
				if (templateType == 2) {//双方
					WordUtil.createHtmlToPdf(data,docConfig.getCrowdsourceBothSidesDeliveryTemplate(),filePath.getAbsolutePath(),contractDocName);
				} else {
					WordUtil.createHtmlToPdf(data, docConfig.getCrowdsourceThreeSidesDeliveryTemplate(), filePath.getAbsolutePath(), contractDocName);
				}
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				throw SmartException.of(e.getMessage());
			}
		}
		return contractDocFile;
	}

	/**
	 * 生成 项目交付文档，返回文件
	 *
	 * @param compid
	 * @param projectIds
	 * @return
	 */
	public List<ExportProjectAcceptanceDto> generatezddProjectDocDeliverFile(int compid, String projectIds) {
		String states = CalcAmountType.getZhiduoduoProjectStates(CalcAmountType.CHECKED);
		//获取当前企业下所有已完成的众包项目,交付/验收文件地址为空的项目
		List<ExportProjectAcceptanceDto> list = projectMapper.getProjectAcceptance(compid, projectIds, states);
		for (ExportProjectAcceptanceDto dto : list) {
			String filePath = generatezddProjectDocDeliverFile(dto).getPath();
			if (StringUtils.isBlank(dto.getDeliveryPath())) {
				dto.setDeliveryPath(filePath);
				new CompanyProject().setProjectid(dto.getProjectid()).setDeliveryPath(filePath).updateById();
			}
		}
		return list;
	}

	public File generatezddProjectDocDeliverFile(ExportProjectAcceptanceDto dto) {

		String fileFolderPath = docConfig.getDeliverDocFilePath() + File.separator + dto.getCompid();
		File filePath = new File(fileFolderPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		String contractDocName = "《项目验收&结算确认单》_" + dto.getCompname() + "_" + DateUtil.getString(dto.getProjectfinish(), DateUtil.FORMAT_STYLE_5) + "_ZDD" + dto.getProjectid() + ".pdf";
		File contractDocFile = new File(filePath, contractDocName);
		if (!contractDocFile.exists()) {
			FileUtils.delete(contractDocFile);

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			if (!sealPath.exists()) {
				sealPath.mkdirs();
			}
			String compseal = dto.getCompname() + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(dto.getCompname(), compsealFile.getAbsolutePath());
				if (!create) {
					throw SmartException.of(StatusMsg.StatusMsg_199);
				}
			}

			Map<String, Object> data = new HashMap<>();
			data.put("publishTime", DateUtil.getString(dto.getPublishTime(), DateUtil.FORMAT_STYLE_3));
			data.put("generalTime", DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_3));
			data.put("projectstart", DateUtil.getString(dto.getProjectstart(), DateUtil.FORMAT_STYLE_3));
			data.put("projectfinish", DateUtil.getString(dto.getProjectfinish(), DateUtil.FORMAT_STYLE_3));
			data.put("compname", dto.getCompname());
			data.put("username", dto.getUsername());
			data.put("projectname", dto.getProjectname());
			data.put("projectAmount", dto.getProjectAmount());
			data.put("moneyChinese", NumberToCN.toChinese(dto.getProjectAmount().toString())); // 人民币大写
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));

			try {
				//使用freemarker 生成pdf文件
				WordUtil.createHtmlToPdf(data,docConfig.getProjectDeliveryTemplate(),filePath.getAbsolutePath(),contractDocName);
			} catch (Exception e) {
				log.error("生成交付文件 报错：", e);
				throw SmartException.of(StatusMsg.StatusMsg_199);
			}
		}
		return contractDocFile;
	}

	/**
	 * 下载  /智众包项目 验收模板
	 *
	 * @param response
	 * @param list
	 */
	public void downloadDeliveryProjectDoc(HttpServletResponse response, List<ExportProjectAcceptanceDto> list) {

		if (!CollectionUtils.isEmpty(list)) {
			//新建一个临时文件夹，将所有文件 都放在这个文件夹下
			String temporaryFolderName = "projectDeliveryFileTemFolder" + System.currentTimeMillis();
			File temporaryFolder = new File(uploadPathConfig.getUserLocal() + temporaryFolderName);
			if (!temporaryFolder.exists()) {
				if (!temporaryFolder.mkdirs()) {
					LogUtil.error("项目验收结算确认-新建临时文件夹失败！");
					return;
				}
			}
			for (ExportProjectAcceptanceDto dto : list) {
				String filename = new File(dto.getDeliveryPath()).getName();
				FileUtil.fileCopy(dto.getDeliveryPath(), temporaryFolder.getPath() + File.separator + filename);
			}

			OutputStream out = null;
			try {
				out = response.getOutputStream();

				// 调用方法打包zip文件
				byte[] zip = FileUtil.createZip(temporaryFolder.getPath());
				// 压缩包名称
				String zipName = "项目验收结算确认" + "-" + DateUtil.DateToStr("yyyy-MM-dd", new Date()) + ".zip";
				response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "utf-8"));
				response.addHeader("Content-Length", "" + zip.length);
				response.setContentType("application/octet-stream;charset=UTF-8");
				IOUtils.write(zip, out);
			} catch (Exception e) {
				LogUtil.error("项目验收结算确认-项目文件夹压缩为压缩包失败！");
			} finally {
				try {
					// 压缩成功后删除之前的临时文件夹
					if (temporaryFolder.exists()) {
						FileUtil.delFiles(temporaryFolder);
					}
					//关闭流
					if (out != null) {
						out.flush();
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
					LogUtil.error("项目验收结算确认文件-将文件夹压缩为压缩包错误！");
				}
			}
		}

	}
	public void downloadProjectEntrusteContractPDF(HttpServletResponse response, EntrustmentProject entrustmentProject,
													 ProjectEntrusteeInfoDto infoDto) {

		// 合同存放路径
		String fileFolderPath = generateEntrustContractFolder(entrustmentProject);

		File contractFile = generateEntrustContractFileInteralPDF(response, infoDto, fileFolderPath);
		if (null == contractFile) {
			returnResponse(response, StatusMsg.StatusMsg_199);
			LogUtil.info("生成委托接单项目合同 失败！");
			return;
		}

		//contract doc exists, download
		try {
			FileUtil.downloadFile(response, contractFile);
		} catch (Exception e) {
			log.error("downloadProjectEntrusteContractPDF", e);
			returnResponse(response, optFailSmartResult());
		}
	}

	private File generateEntrustContractFileInteralPDF(HttpServletResponse response, ProjectEntrusteeInfoDto dto, String fileFolderPath) {
		Asserts.notNull(dto, StatusMsg.StatusMsg_1110);

		String contractNo =
				"WT" + DateUtil.getString(dto.getCreatetime(), DateUtil.FORMAT_STYLE_5) + dto.getImportId() + dto.getEntrusteeId();
		String contractDocName = dto.getEntrusteeStudio() + "-" + dto.getEntrusteeId() + ".pdf";

		BigDecimal serviceCharge = BigDecimal.ZERO;
		String companyName = "";
		if (NumberUtil.equals(dto.getProjectType(), ProjectType.ENTRUST_CROWDSOURCE)) {
			// 委托众包项目，使用主体企业名称
			companyName = dto.getPrincipalName();
			serviceCharge = dto.getProjectAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
		} else {
			companyName = dto.getCompname();
			// 委托接单使用含税金额
			serviceCharge = dto.getTaxInclusiveAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
		}
		String username = dto.getEntrusteeStudio();

		return generateEntrustDocFileInternalPDF(response, contractDocName, contractNo, companyName, CrowdsourceUserType.STUDIO, username,
				dto.getCreatetime(), dto.getName(), dto.getContent(), serviceCharge, fileFolderPath,dto.getPrincipalName());
	}

	/**
	 * 用的还是 的创客合同模板
	 *
	 * @return
	 */
	private File generateEntrustDocFileInternalPDF(HttpServletResponse response, String contractDocName, String contractNo,
													String compname, int userType, String username, Date contractDate, String projectname,
													String projectContent, BigDecimal serviceCharge, String fileFolderPath,String principalName) {

		File filePath = new File(fileFolderPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		File contractDocFile = new File(filePath, contractDocName);

		if (!contractDocFile.exists()) {
			FileUtils.delete(contractDocFile);

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			if (!sealPath.exists()) {
				sealPath.mkdirs();
			}
			String compseal = compname + "_seal.png";
			String userseal = username + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(compname, compsealFile.getAbsolutePath());
				if (!create) {
					returnResponse(response, StatusMsg.StatusMsg_199);
					return null;
				}
			}
			File usersealFile = null;
			if (userType == CrowdsourceUserType.STUDIO) {
				usersealFile = new File(sealPath, userseal);
				// 自然人不需要生成章
				if (!usersealFile.exists()) {
					boolean create = SealUtil.createSimpleCircleSeal(username, usersealFile.getAbsolutePath());
					if (!create) {
						returnResponse(response, StatusMsg.StatusMsg_199);
						return null;
					}
				}
			}
			LocalDate localDate = DateUtil.date2LocalDate(contractDate).plusYears(1).minusDays(1);
			Date endDate = DateUtil.localDate2Date(localDate);
			Map<String, Object> data = new HashMap<>();
			data.put("contractNo", contractNo);
			// 使用企业主体名称
			data.put("compname", compname);
			data.put("username", username);
			data.put("serviceCharge", serviceCharge);
			data.put("contractDate", DateUtil.getString(contractDate, DateUtil.FORMAT_STYLE_3));
			data.put("validity", 1);
			data.put("startYear", DateUtil.getString(contractDate, "yyyy"));
			data.put("startMonth", DateUtil.getString(contractDate, "MM"));
			data.put("startDay", DateUtil.getString(contractDate, "dd"));
			data.put("endYear", DateUtil.getString(endDate, "yyyy"));
			data.put("endMonth", DateUtil.getString(endDate, "MM"));
			data.put("endDay", DateUtil.getString(endDate, "dd"));
			data.put("projectname", projectname);
			data.put("content", projectContent);
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));
			data.put("userseal", usersealFile == null ? "" : ImgBase64Util.ImgToBase64(usersealFile.getAbsolutePath()));
			data.put("principalName",principalName);
			try {
				//生成合同
				WordUtil.createHtmlToPdf(data, docConfig.getZddEntrustedOrderReceiving(), filePath.getAbsolutePath(), contractDocName);
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				returnResponse(response, StatusMsg.StatusMsg_199);
				return null;
			}
		}
		return contractDocFile;
	}

	/**
	 * 下载委托项目合同包含所有子项目的zipPDF包
	 *
	 * @param response      response
	 * @param entrusteeList
	 */
	public void downloadProjectEntrusteeContractZipPDF(HttpServletResponse response, EntrustmentProject entrustmentProject,
														List<ProjectEntrusteeInfoDto> entrusteeList) {

		// 获取企业信息
		Company company = companyMapper.selectById(entrustmentProject.getCompid());
		Asserts.notNull(company, StatusMsg.StatusMsg_302);

		// 合同存放路径
		String fileFolderPath = generateEntrustContractFolder(entrustmentProject);

		// 对每个子项目生成合同文件，并存入文件夹
		List<File> contractList = Lists.newArrayList();
		for (ProjectEntrusteeInfoDto dto : entrusteeList) {
			contractList.add(generateEntrustContractFileInteralPDF(response, dto, fileFolderPath));
		}

		// 生成压缩包
		Asserts.notEmpty(contractList, StatusMsg.StatusMsg_650);
		try (OutputStream out = response.getOutputStream()) {
			// 压缩包名称
			String zipName = company.getCompname() + "-" + DateUtil.DateToStr("yyyy-MM-dd", entrustmentProject.getCreatetime()) + ".zip";
			// 调用方法打包zip文件
			FileUtil.createZip2Response(response, fileFolderPath, zipName);
		} catch (Exception e) {
			log.error("将委托项目文件夹压缩为压缩包失败！", e);
		}
	}

	/**
	 * 生成委托 /创客团  项目交付文档，返回文件
	 *
	 * @param compid
	 * @param list 委托接单（项目-创客）集合
	 * @return
	 */
	public List<ExportProjectAcceptanceDto> generateEntrustZddProjectDocDeliverFile(int compid, List<EntrustmentProjectItemReduceDto> list) {
		String states = CalcAmountType.getEntrustProjectStates(CalcAmountType.FINISHED);
		//获取项目数据
		List<ExportProjectAcceptanceDto> dataList = new ArrayList<>();
		for (EntrustmentProjectItemReduceDto reduceDto : list) {
			dataList.addAll(entrustmentProjectItemMapper.getZddProjectAcceptance(compid, reduceDto.getImportId(), reduceDto.getEntrusteeId(), states));
		}

		for (ExportProjectAcceptanceDto dto : dataList) {
			String filePath = generateEntrustZddProjectDocDeliverFile(dto).getPath();
			if (StringUtils.isBlank(dto.getDeliveryPath())) {
				dto.setDeliveryPath(filePath);
				new EntrustmentProjectBlock().setProjectId(dto.getProjectid())
											 .setEntrusteeId(dto.getUserid())
											 .setItemIds(dto.getItemIds())
											 .setDeliveryPath(filePath)
											 .insert();
			}
		}
		return dataList;
	}

	public File generateEntrustZddProjectDocDeliverFile(ExportProjectAcceptanceDto dto) {

		String fileFolderPath = docConfig.getDeliverDocFilePath() + File.separator + dto.getCompid();
		File filePath = new File(fileFolderPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		String suffix = ProjectType.isEntrustProject(dto.getProjectType()) ? "WTJD" : "CKT";
		String contractDocName = "《项目验收&结算确认单》_" + dto.getCompname() + "_" + dto.getUsername() + "_" + DateUtil.getString(dto.getProjectfinish(), DateUtil.FORMAT_STYLE_5) + "_" + suffix + dto.getProjectid() + ".pdf";
		File contractDocFile = new File(filePath, contractDocName);
		if (!contractDocFile.exists()) {
			FileUtils.delete(contractDocFile);

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			if (!sealPath.exists()) {
				sealPath.mkdirs();
			}
			String compseal = dto.getCompname() + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(dto.getCompname(), compsealFile.getAbsolutePath());
				if (!create) {
					throw SmartException.of(StatusMsg.StatusMsg_199);
				}
			}

			Map<String, Object> data = new HashMap<>();
			data.put("publishTime", DateUtil.getString(dto.getPublishTime(), DateUtil.FORMAT_STYLE_3));
			data.put("generalTime", DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_3));
			data.put("projectstart", DateUtil.getString(dto.getProjectstart(), DateUtil.FORMAT_STYLE_3));
			data.put("projectfinish", DateUtil.getString(dto.getProjectfinish(), DateUtil.FORMAT_STYLE_3));
			data.put("compname", dto.getCompname());
			data.put("username", dto.getUsername());
			data.put("projectname", dto.getProjectname());
			data.put("projectAmount", dto.getProjectAmount());
			data.put("moneyChinese", NumberToCN.toChinese(dto.getProjectAmount().toString())); // 人民币大写
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));

			try {
				//使用freemarker 生成pdf文件
				WordUtil.createHtmlToPdf(data,docConfig.getProjectDeliveryTemplate(),filePath.getAbsolutePath(),contractDocName);
			} catch (Exception e) {
				log.error("生成交付文件 报错：", e);
				throw SmartException.of(StatusMsg.StatusMsg_199);
			}
		}
		return contractDocFile;
	}

	/**
	 * 生成委托智众包/创客团众包 项目交付文档，返回文件
	 *
	 * @param compid
	 * @param list
	 * @param templateType 使用模版 2：智众包双方模版，3：智众包三方模版
	 * @return
	 */
	public List<ExportProjectAcceptanceDto> generateEntrustCroProjectDocDeliverFile(int compid, List<EntrustmentProjectItemReduceDto> list, int templateType) {
		String states = CalcAmountType.getEntrustProjectStates(CalcAmountType.FINISHED);
		//获取项目数据
		List<ExportProjectAcceptanceDto> dataList = new ArrayList<>();
		for (EntrustmentProjectItemReduceDto reduceDto : list) {
			dataList.addAll(entrustmentProjectItemMapper.getCroProjectAcceptance(compid, reduceDto.getImportId(), reduceDto.getEntrusteeId(), states));
		}

		for (ExportProjectAcceptanceDto dto : dataList) {
			List<ExportProjectAcceptanceItemDto> itemList = entrustmentProjectItemMapper.getProjectAcceptanceItemList(dto.getProjectid());
			dto.setList(itemList);

			String filePath = generateEntrustCroProjectDocDeliverFile(dto, templateType).getPath();
			if (StringUtils.isBlank(dto.getDeliveryPath())) {
				dto.setDeliveryPath(filePath);
				new EntrustmentProjectBlock().setProjectId(dto.getProjectid())
											 .setEntrusteeId(dto.getUserid())
											 .setItemIds(dto.getItemIds())
											 .setDeliveryPath(filePath)
											 .insert();
			}
		}
		return dataList;
	}

	/**
	 * 生成众包项目验收文件
	 * @param dto
	 * @param templateType templateType 使用模版 2：智众包双方模版，3：智众包三方模版
	 * @return
	 */
	public File generateEntrustCroProjectDocDeliverFile(ExportProjectAcceptanceDto dto,int templateType) {

		String fileFolderPath = docConfig.getDeliverDocFilePath() + File.separator + dto.getCompid() + File.separator + templateType;
		File filePath = new File(fileFolderPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		String suffix = ProjectType.isEntrustProject(dto.getProjectType()) ? "WTJD" : "CKT";
		String contractDocName = "《项目验收&结算确认单》_" + dto.getCompname() + "_" + dto.getUsername() + "_" + DateUtil.getString(dto.getProjectfinish(), DateUtil.FORMAT_STYLE_5) + "_" + suffix + dto.getProjectid() + ".pdf";
		File contractDocFile = new File(filePath, contractDocName);
		if (!contractDocFile.exists()) {
			FileUtils.delete(contractDocFile);

			//检查公章是否生成了
			File sealPath = new File(docConfig.getSealPath());
			if (!sealPath.exists()) {
				sealPath.mkdirs();
			}
			String compseal = dto.getCompname() + "_seal.png";
			File compsealFile = new File(sealPath, compseal);
			if (!compsealFile.exists()) {
				boolean create = SealUtil.createSimpleCircleSeal(dto.getCompname(), compsealFile.getAbsolutePath());
				if (!create) {
					throw SmartException.of(StatusMsg.StatusMsg_199);
				}
			}

			Map<String, Object> data = new HashMap<>();
			data.put("publishTime", DateUtil.getString(dto.getPublishTime(), DateUtil.FORMAT_STYLE_3));
			data.put("generalTime", DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_3));
			data.put("compname", dto.getCompname());
			data.put("partyname", dto.getPartyname());
			data.put("projectname", dto.getProjectname());
			data.put("projectAmount", dto.getProjectAmount());
			data.put("moneyChinese", NumberToCN.toChinese(dto.getProjectAmount().toString()));
			for (ExportProjectAcceptanceItemDto item : dto.getList()) {
				item.setProjectAmountChinese(NumberToCN.toChinese(item.getProjectAmount().toString()));// 人民币大写
				item.setIntegratedTaxFeeChinese(NumberToCN.toChinese(item.getIntegratedTaxFee().toString()));// 人民币大写
			}
			data.put("list", dto.getList());
			data.put("compseal", ImgBase64Util.ImgToBase64(compsealFile.getAbsolutePath()));

			try {
				//使用freemarker 生成pdf文件
				if (templateType == 2) {//双方
					WordUtil.createHtmlToPdf(data,docConfig.getCrowdsourceBothSidesDeliveryTemplate(),filePath.getAbsolutePath(),contractDocName);
				} else {
					WordUtil.createHtmlToPdf(data, docConfig.getCrowdsourceThreeSidesDeliveryTemplate(), filePath.getAbsolutePath(), contractDocName);
				}
			} catch (Exception e) {
				log.error("使用freemarker 生成合同 报错：", e);
				throw SmartException.of(e.getMessage());
			}
		}
		return contractDocFile;
	}

}
